Does the Ruby method lookup start from the bottom

2019-08-26 11:22发布

问题:

I'm starting to learn more about the Ruby object model, and am trying to understand the flow of how methods are found.

As I understand it, an object searches for a method by checking it's self class (going to the right) and if the method is not found there, it goes up the ancestor hierarchy.

What I'm confused about though is... when it looks into a class, does it read each method from the bottom up, or from the top down?

I'm thinking the former. But if that's true, then it strikes me as counterintuitive to what I've always understood about how programs are read/interpreted -- from the top down.

Can someone confirm my understanding of this. Thanks.

回答1:

later declarations override earlier ones -

class Foo
  def hello
    'hello first'
  end

  def hello
    'hello second'
  end
end

f = Foo.new

puts f.hello # hello second