Ruby方法查找是从类的底部开始并向上,还是从顶部开始并向下? [英] Does the Ruby method lookup start from the bottom of a class and go up, or from the top and go down?

查看:110
本文介绍了Ruby方法查找是从类的底部开始并向上,还是从顶部开始并向下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习有关Ruby对象模型的更多信息,并试图了解如何找到方法的流程.

据我了解,对象通过检查自身的类(向右移动)来搜索方法,如果在该方法中未找到该方法,则该对象将沿祖先层级上移.

我感到困惑的是……当它进入一个类时,它是从下至上还是从上至下读取每个方法?

我在想前者.但是,如果这是真的,那会让我觉得与我一直以来对如何读取/解释程序的理解背道而驰(从上至下).

有人可以确认我对此的理解.谢谢.

解决方案

后来的声明会覆盖先前的声明-

class Foo
  def hello
    'hello first'
  end

  def hello
    'hello second'
  end
end

f = Foo.new

puts f.hello # hello second

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.

解决方案

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

这篇关于Ruby方法查找是从类的底部开始并向上,还是从顶部开始并向下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆