将对象从一类传递到另一类

时间:2020-07-21 10:27:14

标签: ruby

这里的代码有效,但我希望使其尽可能简洁,以得到输出而不必构建哈希。

class Person
  attr_accessor :name, :age
  
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def create
    Report.create({name: @name, age: @age})
  end
end

class Report < Person
  
  def self.create(attributes)
    puts "Hello, this is my report. I am #{attributes[:name]} and my age is #{attributes[:age]}."
  end
end

me = Person.new("Andy", 34)
me.create # Hello, this is my report. I am Andy and my age is 34.

这里的更改没有用,但是有没有办法?

def create
  Report.create
end

def self.create(attributes)
  puts "Hello, this is my report. I am #{:name} and my age is #{:age}."
end

但输出为“我叫名字,我的年龄是年龄。”

1 个答案:

答案 0 :(得分:1)

您可以像这样通过这个人:

class Person
  attr_accessor :name, :age
  
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def report
    Report.new(self)
  end
end

class Report
  attr_accessor :person
  
  def initialize(person)
    @person = person
  end

  def to_s
    "Hello, this is my report. I am #{person.name} and my age is #{person.age}."
  end
end

me = Person.new("Andy", 34)
puts me.report
# Hello, this is my report. I am Andy and my age is 34.

请注意,我已经更改了一些详细信息:

  • Report不继承自Person
  • Report实例是通过new
  • 创建的
  • Person#create现在为Person#report
  • Report使用to_s作为输出(由puts调用)