In Ruby what does the “receiver” refer to?

回眸只為那壹抹淺笑 提交于 2019-11-29 16:27:11

问题


I'm reading a document that talks about a method having a receiver. What's a receiver?


回答1:


In Ruby (and other languages that take inspiration from SmallTalk) objects are thought of as sending and receiving 'messages'.

In Ruby, Object, the base class of everything, has a send method: Object.send For example:

class Klass
  def hello
    "Hello!"
  end
end
k = Klass.new
k.send :hello   #=> "Hello"
k.hello         #=> "Hello"

In both of these cases k is the receiver of the 'hello' message.




回答2:


In the original Smalltalk terminology, methods on "objects" were instead refered to as messages to objects (i.e. you didn't call a method on object foo, you sent object foo a message). So foo.blah is sending the "blah" message, which the "foo" object is receiving; "foo" is the receiver of "blah".




回答3:


the object before the .

think of calling a method x.y as saying "send instruction y to object x".

it's the smalltalk way of thinking, it will serve you well as you get to some of Ruby's more advanced features.



来源:https://stackoverflow.com/questions/916572/in-ruby-what-does-the-receiver-refer-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!