Ruby – Method and Messages

https://rubytapas.dpdcart.com/subscriber/post?id=45#files

Just subscribed rubytapas, and watching some more episodes. The above talks about method and messages (requires subscription).

As ruby can call a method without parenthesis, we cannot refer a function object in the format of “value = obj.method” (it actually calls the method, instead of just refering it). Ruby doesn’t have a concise way of storing function object in a variable. Instead, it requires “value = obj.method(:method_name)” or “value = Proc.new { do_something }” kind of expressions.

Semantically, ruby focuses on a “message” for external communication between objects rather than a procedural “method”. In the above episode, it’s summarized as follows.

  • A message is a name for a responsibility which a object may have
  • A method is a named, concrete piece of code that encodes one way a responsibility may be fulfilled.

Ruby objects/classes can be dynamically extended, and content of a method can be changed during the code execution. A method refers to specific code block when it’s refered, but a message (send method) just gets a response from the object.

class A
  def test
    puts "A:test"
  end
end

module B
  def test
    puts "B:test"
  end
end

a = A.new

a.send(:test)
  # => A:test
m1 = a.method(:test)

a.extend(B)

a.send(:test)
  # => B:test
m2 = a.method(:test)

m1.call
  # => A:test
m2.call
  # => B:test
Advertisements

Posted on March 2, 2013, in Ruby. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: