问题描述
所以,我对Ruby是一种完全面向对象的语言感到好奇.我偶然发现了一个我并不十分清楚的问题.
So, I'm curious as to how Ruby is a fully object oriented language. I stumble over one problem that isn't really clear to me.
如果我定义如下函数
def foo(text)
print text
end
并且我在类之外定义函数,该函数如何成为对象?我意识到我可以打电话
and I define the function outside of a class, how is this function an object? I realize that I can call
foo.class
我得到了NilClass.这是否意味着foo是NilClass的实例?如果是的话,当我打电话时这到底是什么意思
And I get NilClass. Does this mean that foo is an instance of NilClass? And if it is, what does it mean exactly when I call
foo "hello world"
如果foo是一个对象,则在执行上述声明时我将调用什么方法.另外,如果它是一个对象,那是否意味着我可以对其进行修改并向其中添加其他方法(例如,栏),我可以在其中声明以下内容:
If foo is an object, what method am I calling when I make the statement as above. Also, if it an object, does that mean I can modify it and add another method to it (say bar) where I could possibly make the following statment:
foo.bar(some variables)
对不起,我对此有点困惑.任何澄清非常感谢!谢谢!
Sorry, I'm just a little confused on this point. Any clarification is very much appreciated! Thanks!
推荐答案
- 用户定义的全局函数(顶级函数)是
Object
的实例方法(即使self
的类不是Object
). - 顶级方法始终是私有的.
- User defined global functions (top-level functions) are instance methods of
Object
(even though the class ofself
is notObject
). - Top-level methods are always private.
这篇关于Ruby如何完全面向对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!