Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby `send` vs `call` method

Tags:

ruby

I'm reading an article about Ruby 1.9. There are a lot of uses of the call method with Object.

But with a recent version of Ruby, I get this:

BasicObject.methods.include? :send # => true
BasicObject.methods.include? :call # => false
Object.methods.include? :call # => false

def foo
  puts 'text'
end

Object.send :foo # => text
Object.call :foo # => NoMethodError: undefined method `call' for Object:Class

I think that in some version of Ruby (probably 1.9), method was renamed. But I'm not sure. Please make it clear.

like image 354
Mike Belyakov Avatar asked Feb 15 '16 01:02

Mike Belyakov


1 Answers

To begin with, send and call are two very different methods.

In ruby, the concept of object orientation takes its roots from Smalltalk. Basically, when you call a method, you are sending that object a message. So, it makes sense that when you want to dynamically call a method on an object, the method you call is send. This method has existed in ruby since at least 1.8.7.

In ruby, we also have a concept of "blocks". Blocks are the do...end things attached to the end of method calls. Blocks can be traditionally yielded to; or, it is entirely possible to create an object out of a block (a Proc), and pass that around. In order to execute the block, you can call call on the block.

call has never been defined on Object, whereas send is defined on everything.

(note: for some reason, call doesn't seem to have documentation in the 2.3.0 documentation; however, it still exists and does the same thing from 2.2.0, so I linked that one instead.)

like image 160
Jeremy Rodi Avatar answered Oct 17 '22 13:10

Jeremy Rodi