Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Kernel method looked up only when `send` is used?

Tags:

ruby

I should be able to call Kernel methods on every object, and method format is defined on Kernel. Why is method_missing invoked on Kernel with the third example?

class A
  def method_missing(meth, *args, &block)
    if meth == :foo
      puts 'ok'
    elsif meth == :format
      puts 'ok'
    end
  end
end

a = A.new
a.foo           # => ok
a.send(:foo)    # => ok
a.format        # => ok
a.send(:format) # => too few arguments (ArgumentError)
like image 249
Malte Rohde Avatar asked May 22 '14 12:05

Malte Rohde


1 Answers

That is because Kernel#format is a private method. When you call it using send, which means you are calling it without an explicit receiver, the defined method is called, and argument error is raised. When you call it with an explicit receiver, the method is not found because the defined one is private, and so method_missing is invoked.

like image 89
sawa Avatar answered Nov 06 '22 19:11

sawa