需要知道Ruby的--Messages, not Function Calls

Messages, not Function Calls

Java Programmers tend to think of obj.method() as looking up a member function in a table and calling it.

Ruby programmers tend to think of obj.method as sending a message to an object.

What’s the Difference?

The difference is subtle, but important!




class VCR
  def initialize
    @messages = []
  end
  def method_missing(method, *args, &block)
    @messages << [method, args, block]
  end
  def play_back_to(obj)
    @messages.each do |method, args, block|
      obj.send(method, *args, &block)
    end
  end
end


vcr = VCR.new
vcr.sub!(/Java/) { "Ruby" }

vcr.upcase!
vcr[11,10] = "Universe"
vcr << "!"

string = "ddddd Java World"
puts string

vcr.play_back_to(string)
puts string

#JAVA是Call funcation,而Ruby是Send Message,它俩是有区别的。Send Msg只是发送一个消息,因此消息可“存储”后“播放”。method_missing是ruby的一个特殊方法,没有定义的方法的调用都会转去调用它。&block是block回调。
上面的执行流程是:
vcr.sub!(/Java/) { "Ruby" } #进地一个替换,Java换成Ruby,此方法没有,因此执行了method_missing方法,“存"下了这个Send Message
vcr.upcase! #转成大写
vcr[11,10] = "Universe"#将11位置后面换成"Universe"
wcr<<"!" #添加"!"
以上四个方法是存在了@messages中,最后程序中调用play_back_to进行了回放(也就是真正的调用)产生的结果为
这真的很微妙!
Hello Java World
HELLO RUBY Universe!

你可能感兴趣的:(java,Ruby,UP)