![](/img/trans.png)
[英]Accessing Ruby Class Variables with class_eval and instance_eval
[英]Ruby metaprogramming: instance_eval and 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
的對象的instance_eval
。 class_eval
塊的理解:通過打開調用它的對象的類,對塊中的代碼進行評估,就好像放置了該代碼一樣。 因此,在上述情況下,我對class_eval
感到困惑! 我期待class_eval
公交意味着評估在塊class
總線類的。 你可以參考這個階級,真棒文章instance_eval
,為什么乘客沒有被添加到對象。
TL; DR:
Bus.class_eval will
創建實例方法,而Bus.instance_eval
將創建類方法。
現在,關於目標的行為(可以在實例上調用)..... define方法在class_eval
或instance_eval
內部使用時, class_eval
通常行為的影響 。 為什么?。
因為文檔中是這樣說的。 根據文檔:
define method-在接收方中定義一個實例方法。
因此,如果在class_eval
或instance_eval
使用define_method
class_eval
,它將始終創建一個實例方法。
希望這對您有所幫助:-)。
基本上,使用def
時無法對類對象執行instance_eval
。 這是使用instance_eval
和class_eval
的一般方法。 http://web.stanford.edu/~ouster/cgi-bin/cs142-winter15/classEval.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.