淺析 Ruby 裡的幾個動态方法 (一),send 方法

第一次寫技術方面的貼,歡迎拍磚 :)
動态方法,是去控制靜态方法的方法,讓靜态方法的方法名和方法的内容會根據參數的變化而變化,簡而言之,他使方法成為了一個變量。讓我們通過一個多态執行個體,來了解一下最簡單的動态方法send。
所謂多态就是把不同種類的東西當作相同的東西來處理。比如我要打開三個箱子,打開的方法都不同,如果發出同樣打開箱子的指令,3個人都會以自己的方法來打開箱子。在程式設計中,“打開箱子”的指令,我們稱之為消息;而打開不同箱子的具體操作,我們稱之為方法。
示範程式:
def box1.open
puts("open box")
end
def box2.open
puts("open lock and open box")
end
def box3.open
puts("It's a open box")
end
這裡設定了box1、box2、box3三個對象,但是當我們預先并不知道要調用哪一個box方法時,就會寫出類似下列這樣的when……case表達式,在面向對象中這種寫法是較為醜陋的:
def open(num)
case num
when 1;puts("open box")
when 2;puts("open lock and open box")
when 3;puts("It's a open box")
when 4;puts("I can't open box")
when 5;puts("Oh shit box!")
end
end
box.open(1)
如果我們加上使用send方法,就可以将case……when給解藕,使程式降低了耦合性,增加了拓展性。send方法的作用是将一個方法傳遞給對象,例:
1.send(:+,2)
=>3
下面的例子是解藕def open(num)
class Box
def open_1
puts "open box"
end
def open_2
puts "open lock and open box"
end
def open_3
puts "It's a open box"
end
def open_4
puts "I can't open box"
end
def open_5
puts "Oh shit box!"
end
end
box = Box.new
box.send("open_#{num}")
這樣,将num作為參數,用的open_*num*方法。
但這裡需要注意的是,send方法太過強大,可以調用任何方法,包括私有方法,使用public_send方法将能夠尊重方法接受者的隐私權,可以用它來代替send方法。