Ruby Method Call Hierarchy

Inspired by this article , I played with the Ruby method, invoking a hierarchy and noticing something strange.

Given:

class B
  def foo  
    "- Instance method defined by B"
  end  

  def method_missing(method)
    puts "- method_missing (#{method}) on b. Redirecting to b.foo\n"
    foo
  end
end

b = B.new

def b.foo  
  "- Method defined directly on an instance of B\n" + super  
end

def b.method_missing(method)
  "- method_missing (#{method}) on b. Calling super\n" + super
end

puts "Calling 'bar' on b of type #{b.class}:"
puts b.bar

Running it gives:

Calling 'bar' on b of type B:
- method_missing (bar) on b. Redeirecting to b.foo
- method_missing (bar) on b. Calling super
- Method defined directly on an instance of B
- instance method defined by B

My question is:

Since I call b.bar (on the object), how is the class instance method called before the objet object instance method is called?

I would expect it to b.method_missing(method)be called first, and then an instance of the class method_missing(method)(as I call super, but super is the class hierarchy ...), which does the redirection from barto foo. Also, how did it happen, after redirecting to the foomissing_method instance? They just told us that we were redirected ...

, , Ruby ( ), ( ).

, , , ...

+5
1

, . :

method_missing (bar) on b. Redeirecting to b.foo
method_missing (bar) on b. Calling super

, B#method_missing singleton b.method_missing, , . , , b.method_missing . , , puts b.bar:

  • b bar, b.method_missing 'bar' .
  • b.method_missing B#method_missing super.
  • B#method_missing puts , .
  • singleton b.foo
  • puts, b.method_missing b.foo
+4

All Articles