2012-04-27 74 views
2

我希望能夠動態名稱方法(我不會離開它的用戶輸入要做到這一點,但作爲一個例子):動態方法命名

puts "" 
foo = gets 
def (whatever the user inputted for foo) 
end 

我怎樣才能做到這一點?

回答

3

您可以使用send方法通過使用參數:define_method向該類發送消息告訴它您將要爲該類定義新方法。

例如,具有一個類Car

class Car 
end 

c = Car.new 

c.sound甲呼叫帶來的誤差

NoMethodError: undefined method `sound' for #<Car:0x29d9048> 

但是,在定義該方法的名稱,並把它發送到後級:

input = "sound" 

Car.send(:define_method, input) do 
    puts "vroom!" 
end 

致電c.sound現在使輸出

vroom! 
0

最常用的方法是:define_methodclass_evalinstance_eval。定義method_missing方法也用了很多。

#An example of class_eval 
class Foo 
end 

foo = gets.chomp 
#suppose you input bar here 
Foo.class_eval %Q{ 
    def #{foo} 
    puts "This is #{foo} method you defined!" 
    end 
} 
Foo.new.bar 
#output: This is the bar method you defined! 

instance_eval以類似的方式使用,但在一個類的實例中定義。 define_method也相似:

#An example of define_method 
klass = Class.new 
foo = gets.chomp 
#suppose you typed bar 
klass.send(:define_method,foo) do 
    puts "This is #{foo} method you defined!" 
end 
klass.new.bar 
#output: This is bar method you defined! 

搜索「紅寶石元編程」和有很多教程在那裏。