如何實現Ruby向對象發送消息
Ruby語言做為一種解釋型面完全面向對象的腳本語言,值得我們去深入研究。我們可以利用Ruby向對象發送消息。下面將為大家詳細介紹相關方法。#t#
我們可以直接實現Ruby向對象發送消息:
- class HelloWorld
- def say(name)
- print "Hello, ", name
- end
- end
- hw = HelloWorld.new
- hw.send(:say,"world")
我們通常使用hw.say("world"),但send可以對private的方法起作用。 不光如此send可以使程序更加動態,下面我們看看一個例子:
我們定義了一個類Person,我們希望一個包含Person對象的數組能夠按照Person的任意成員數據來排序實現Ruby向對象發送消息:
- class Person
- attr_reader :name,:age,:height
- def initialize(name,age,height)
- @name,@age,@height = name,age,height
- end
- def inspect
- "#@name #@age #@height"
- end
- end
在ruby中任何一個類都可以隨時打開的,這樣可以寫出像2.days_ago這樣優美的code,我們打開Array,并定義一個sort_by方法:
- class Array
- def sort_by(sysm)
- self.sort{|x,y| x.send(sym)
<=> y.send(sym)}- end
- end
我們看看運行結果:
- people = []
- people << Person.new("Hansel",35,69)
- people << Person.new("Gretel",32,64)
- people << Person.new("Ted",36,68)
- people << Person.new("Alice", 33, 63)
- p1 = people.sort_by(:name)
- p2 = people.sort_by(:age)
- p3 = people.sort_by(:height)
- p p1 # [Alice 33 63, Gretel 32
64, Hansel 35 69, Ted 36 68]- p p2 # [Gretel 32 64, Alice 33
63, Hansel 35 69, Ted 36 68]- p p3 # [Alice 33 63, Gretel 32
64, Ted 36 68, Hansel 35 69]
這個結果是如何得到的呢?
其實除了send外還有一個地方應該注意attr_reader,attr_reader相當于定義了name, age,heigh三個方法,而Array里的sort方法只需要提供一個比較方法:
x.send(sym) <=> y.send(sym) 通過send得到person的屬性值,然后在使用<=>比較。
以上就是Ruby向對象發送消息的一些方法技巧講解。