1.send的用法
在RUBY中可以在运行时,来决定那个对象被调用,send方法就是做这个的,他接受一个symbol变量为参数。
首先来个非常非常的简单的例子:
class Foo
def foo
"aa"
end
end
puts Foo.new.__send__(:foo)
当然也可以使用send方法,不过为了和可能出现的自己类中定义的send方法区别,推荐使用__send__方法
在1.9中,send方法不能调用private方法了,不过我们能够使用__send!来调用:
class Foo
private
def foo
"aa"
end
end
p Foo.new.__send!(:foo) # => nil
p Foo.new.send(:foo) #private method `foo' called for #<Foo:0xa89530> (NoMethodError)
下面有个排序的比较全的例子:
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
class Array
def sort_by(sym) # Our own version of sort_by
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]