一亿蒸、使用define_method定義單例方法
一般而言對類使用define_method方法時,定義的都是實例方法。該方法需要接收方法名作為參數(shù)闽晦,并且接收一個代碼塊。
需要注意的是當使用{}
代碼塊而不是 do...end代碼塊時提岔,需要將方法名帶上括號仙蛉,否則ruby不能正常解析語法。
class Apple
define_method(:hello) {
"hello,world"
}
define_method(:say) do |word|
"I say #{word}"
end
end
這樣就在Apple類中定義了兩個實例方法碱蒙,分別是hello和say方法
可以這樣調(diào)用:
a = Apple.new
a.hello
=> "hello,world"
a.say("nice weather today")
=> "I say nice weather today"
當然我們也可以使用define_method來定義單例方法:
1.定義類方法荠瘪,可以這樣做:
class << Apple #打開Apple類的單例類
define_method :show do
"I'm Apple's singleton class"
end
end
然后就可以直接調(diào)用這個類方法:
Apple.show
=> "I'm Apple's singleton class"
2.對實例定義單例方法,可以這樣做:
class << a
define_method :talk do
"create a's singleton method"
end
end
a.talk
=> "create a's singleton method"
二赛惩、使用define_singleton_method定義單例方法
define_singleton_method方法可以直接定義單例方法(此處是類方法)
該方法需要接收方法名作為參數(shù)哀墓,并且接收一個代碼塊
class Human
define_singleton_method :run do |num|
"I can run #{num} km per hour"
end
end
然后調(diào)用這個單例方法:
Human.run(10)
=> "I can run 10 km per hour"
三、define_method和define_singleton_method的效能問題
使用define_method和define_singleton_method可以動態(tài)定義方法喷兼,但它們要比直接使用def關(guān)鍵字定義方法的效率慢篮绰。