【问题标题】:Create instance of a new class object, from within separate class object从单独的类对象中创建新类对象的实例
【发布时间】:2015-11-17 01:29:03
【问题描述】:

在 Ruby 中是否可以使用类方法实例化不同类的另一个对象?

我花了很多时间研究 Google、Ruby 文档和 Stack Overflow 以找到我的查询的答案,但无济于事,所以我将这个问题作为最后的手段发布。

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

User 类中有 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 我想初始化一个新对象并将其发送到 Blog 类。

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

【问题讨论】:

  • 如果实例化一个用户对象: harry = User.new("harry1") - 将 harry.user 结果放入:#<0x007fdc530c2f60>

标签: ruby class object methods


【解决方案1】:

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

您想让用户的blogs 属性拥有一个博客数组吗?因为您的代码只是将日期文本元组放入数组中。

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

  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

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

【讨论】:

  • 谢谢!这些都是非常有用的解决方案。但是我当时期待我能够将这个新对象称为 Blog 的实例,因为它是使用上面的 Blog.new 创建的,这可能吗?
  • 是的。它只取决于最后一行,它告诉 ruby​​ 你在方法中返回什么。在我的实现中,新的 Blog 对象被返回,你可以在它上面调用其他方法。
  • 你也可以通过用户访问博客,比如:harry.blogs[0].text
【解决方案2】:

看起来您的代码有一些缺陷。这是更正后的代码: 您没有使用 @ 为实例变量赋值,而是将日期放入 @blogs,而不是 Blog 对象。

如果要将User 的实例从add_blog 传递给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"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-18
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    相关资源
    最近更新 更多