中关村村草 发表于 2011-02-24 10:48

Ruby 面向对象编程的一些高级应用

转:dtrex


Ruby 面向对象编程的一些高级应用




1.send的用法


在RUBY中可以在运行时,来决定那个对象被调用,send方法就是做这个的,他接受一个symbol变量为参数。


首先来个非常非常的简单的例子:


Ruby代码class Foo
   def foo
      "aa"
   end
end

puts Foo.new.__send__(:foo)
当然也可以使用send方法,不过为了和可能出现的自己类中定义的send方法区别,推荐使用__send__方法



在1.9中,send方法不能调用private方法了,不过我们能够使用__send!来调用:
Ruby代码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)   下面有个排序的比较全的例子:


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


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   #
p p2   #
p p3   #

2gua 发表于 2011-02-24 12:32

Ruby的OO还是很强大的,结合Mixin,更是如此啊。

bugbugbug3 发表于 2011-02-24 13:06

"在1.9中,send方法不能调用private方法了"
这个说的不对吧。
页: [1]
查看完整版本: Ruby 面向对象编程的一些高级应用