这里的代码有效,但我希望使其尽可能简洁,以得到输出而不必构建哈希。
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
但输出为“我叫名字,我的年龄是年龄。”
答案 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
调用)