How to understand the sender and receiver in Ruby?

I find it difficult to understand the real meaning of the sender and receiver in Ruby. What do they mean at all? For now, I just understand them as a method call and one that takes a return value. However, I know that my understanding is far from enough. Can someone give me a specific explanation of the sender and receiver in Ruby?

+5
source share
6 answers

The basic concept in Object Orientation is messaging and early conceptualization, borrowed a lot from the Actor Computation Model. Alan Kay, the guy who coined the term “Object Oriented” and invented one of the first OO SmallTalk languages, regretted using a term that instead focuses on objects from messages that he considered a stronger idea .

Speaking of the message, there is a natural "sender" and "recipient" of the message. The sender is the object that calls the method, the receiver is the object whose method is called. In Ruby, if you call a method without explicitly naming the object, it sends the method name and its arguments as a message to the default recipient self.

OO "", " " " " - . "", " , ", " " .

+7

Ruby , , , . ,

"this is a string".reverse
"this is a string".send(:reverse) # equivalent

, , , : , ,

=> "gnirts a si siht"

.

, , :

"this is a string".respond_to?(:reverse)
=> true
Hash.new.respond_to?(:reverse)
=> false

irb. , API-, Twitter ( ), , , , " , ".

+3

:

a = "test123"

" " .

a.reverse ## '321tset' #everything is backwards

? ? ?

  • "reverse" - . . , .
  • a .
  • , . self, main.

, .

+1

, "" "". , "" .

:

def foo argument
  object.bar(argument)
end

foo bar. object bar.

0

, Smalltalk. : . - .

obj.do_somthing self, "hey obj, please do_something". obj do_something- .

class A
  def foo(obj)
    obj.send(:object_id) 
  end
end
a = A.new
b = Object.new
a.foo(b)
=> 4232

In this example, ais the "sender", and b- the "receiver".

0
source

"1234" .reverse

  • The message is “reverse,” and it must correspond to a method called reverse. In other words, you can think of a method as a “message."
  • the receiver is a string object "1234"
  • and the sender is the object in which the method is called. In this case, it should be (itself, which should be) the main one.
0
source

All Articles