从单独的类对象中创建新类对象的实例

时间:2015-08-23 15:47:34

标签: ruby class object methods

Ruby可以使用类方法实例化另一个类的另一个对象吗?

我花了很多时间无法研究Google,Ruby文档和Stack Overflow,以获得我的查询答案,因此我将此问题作为最后的手段发布。

两个类,用户博客。在下面的用户中,我尝试为 Blog 创建一个对象的新实例,并继承一些属性。

在课程用户中有2种方法;

class User
  attr_accessor :blogs, :username

  def initialize(username)
    self.username = username
    self.blogs = []
  end

  def add_blog(date, text)
    self.blogs << [Date.parse(date),text]
    new_blog = [Date.parse(date),text]
    Blog.new(@username,date,text)
  end
end

使用上面的 add_blog 我想初始化&amp;将新对象发送到Blog类。

class Blog
  attr_accessor :text, :date, :user
  def initialize(user,date,text)
    user = user
    date = date
    text = text
  end
end

2 个答案:

答案 0 :(得分:1)

是的,可以使用类方法实例化另一个类的另一个对象。我们ruby程序员一直在这样做。

您是否希望用户的blogs属性拥有一系列博客?因为你的代码只是将日期文本tupel放入数组中。

我认为你想在你的用户类中做这样的事情:

  def add_blog(date, text)
    parsed_date = Date.parse(date)
    new_blog = Blog.new(@username, parsed_date, text)
    self.blogs << new_blog
    new_blog 
  end

我已经逐步展示了它,但你可以组合几行。最后一行返回新博客,如果您只希望博客成为博客数组的一部分,则可能不需要它。

答案 1 :(得分:1)

看起来您的代码存在一些缺陷。这是更正后的代码: 您没有使用@为实例变量分配值,而是在@blogs而不是Blog对象中添加日期。

如果您想将User的实例从Blog传递给add_blog,则可以使用self代表User类的当前实例。如果您只想携带一些属性,那么您可以使用@attribute_nameself.attribute_name语法引用属性

require "date"
class User
  attr_accessor :blogs, :username

  def initialize(username)
    @username = username
    @blogs = []
  end

  def add_blog(date, text)
    @blogs << Blog.new(@username, Date.parse(date),text)
    self
  end

  def to_s
    "#{@username} - #{@blogs.collect { |b| b.to_s }}"
  end
end

class Blog
  attr_accessor :text, :date, :user

  def initialize(user,date,text)
    @user = user
    @date = date
    @text = text
  end

  def to_s
    "Blog of #{user}: #{@date} - #{@text}"
  end
end

puts User.new("Wand Maker").add_blog("2015-08-15", "Hello")
# => Wand Maker - ["Blog of Wand Maker: 2015-08-15 - Hello"]