【发布时间】:2018-08-17 05:07:34
【问题描述】:
def printer_outside_class(value)
puts value
end
class Prints
attr_accessor :value
def initialize(a)
@value = a
end
printer_outside_class(@value)
end
Prints.new(100)
我没有得到任何输出,而是抛出警告“实例变量@value 未初始化”。 Ruby 逐行执行类,所以在调用initialize 函数之前,printer_outside_class(value) 被调用。
是否有可能以某种方式将变量value 传递给外部printer_outside_class(@value) 函数调用?
value 应该从外部传递,不需要通过构造函数。
注意:我可以随意更改构造函数,向Prints 类添加任意代码,添加一个新类并可以随意调用Prints 类。但是,我将无法在函数定义中移动函数调用 printer_outside_class(@value)。
【问题讨论】: