Ruby中的方法访问 [英] Method access in Ruby
本文介绍了Ruby中的方法访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby如何允许隐式允许类之外的类访问方法?
How is it that Ruby allows a class access methods outside of the class implicitly?
示例:
class Candy
def land
homer
end
end
def homer
puts "Hello"
end
Candy.new.land #Outputs Hello
推荐答案
"homer"方法的定义是将该方法添加到Object类中.它没有定义自由功能.
The definition of the "homer" method is adding the method to the Object class. It is not defining a free function.
Candy类隐式继承自Object,因此可以访问Object中的方法.当您在"land"方法中调用"homer"时,方法解析无法在当前类中找到定义,而是转到超类,找到已添加到Object的方法,然后调用它.
Class Candy implicitly inherits from Object, and so has access to the methods in Object. When you call "homer" in the "land" method, the method resolution can't find a definition in the current class, goes to the super class, finds the method you have added to Object, and calls it.
这篇关于Ruby中的方法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文