【发布时间】:2023-03-25 06:33:01
【问题描述】:
我是一个新的 Rubyist,目前我将在类中使用 Struct 来创建一个临时对象。但是,当我像这样在 Struct 中使用成员时遇到一个问题:
class A
attr_accessor :b
B = Struct.new(:name, :print_name) do
def print_name
p "Hello #{name}"
end
end
def initialize(input_name)
@b = B.new(input_name)
end
end
a = A.new('Leo')
a.b.print_name # Hello Leo
但当我的 Struct B 参数不包含 :print_name 时,我也会收到相同的结果。
B = Struct.new(:name) do
...
end
那么有什么不同呢?什么时候应该使用成员参数,什么时候不使用?
谢谢
【问题讨论】: