(大编辑,我已经完成了其中的一部分……)我一直在破解,我想出了一个方法来指定在读取属性之前需要完成的事情:
class Class
def attr_reader(*params)
if block_given?
params.each do |sym|
define_method(sym) do
yield
self.instance_variable_get("@#{sym}")
end
end
else
params.each do |sym|
attr sym
end
end
end
end
class Test
attr_reader :normal
attr_reader(:jp,:nope) { changethings if @nope.nil? }
def initialize
@normal = "Normal"
@jp = "JP"
@done = false
end
def changethings
p "doing"
@jp = "Haha!"
@nope = "poop"
end
end
j = Test.new
p j.normal
p j.jp
但是changethings
不被认为是一种方法——有人有什么想法吗?