似乎我很困惑這兩種方法雖然我一直在使用它們一段時間,但我不明白爲什麼方法乘客未被添加到下面的代碼中的對象:Ruby元編程:instance_eval和class_eval
class Bus
def number_of_seats
42
end
end
Bus.class_eval do
define_method :number_of_windows do
number_of_seats
end
def fuel_type
:diesel
end
end
Bus.instance_eval do
define_method :destination do
'Paris'
end
def passengers
12
end
end
bus = Bus.new
bus.number_of_windows # => 42
bus.fuel_type # => :diesel
bus.destination # => "Paris"
bus.passengers # => undefined method `passengers' (NoMethodError)
注意:
- 試過
instance_eval
第一,只是隨機使用class_eval
,然後它也似乎工作! - 我對
instance_eval
的塊的理解:塊中的代碼與self
一起運行,設置爲調用instance_eval
的對象。 - 我對
class_eval
的塊的理解:通過打開調用它的對象的類來評估塊中的代碼,就好像它的代碼一樣。因此,我對上述案例中的class_eval
感到困惑!我期待class_eval
總線將意味着評估在總線類別class
塊。
乘客方法正常:'Bus.passengers#=> 12'。將'Bus.instance_eval'更改爲'Bus.class_eval'以使乘客成爲實例方法。 – 2015-02-08 06:47:41
你也可以使用'Bus.send(:define_method,:passengers){12}'。 – 2015-02-08 07:00:14
除了'如何工作',這絕對是非常奇怪的行爲。 – Renra 2015-02-08 07:29:47