开发者

If I define a method in Ruby, does it belong to any class?

开发者 https://www.devze.com 2023-01-08 06:10 出处:网络
I have feeling, that if one defines a method def test puts \'Hi\' end then there is a class to which this method belongs to (i.e. Unknown#test). So one probably has a possibility to list all method

I have feeling, that if one defines a method

def test
  puts 'Hi'
end

then there is a class to which this method belongs to (i.e. Unknown#test). So one probably has a possibility to list all methods defined开发者_开发技巧 "outside" of other classes. Or there is another way to do such listing?


If you define a method outside of any class, it will become a private method of the Object class.


A top-level method is a private method of Object. Check out this question.


In future, to find what object a method belongs to, do this:

method(:test).owner

Output, for your example is Object


And you can then list all the methods of Object with

Object.send(:methods)

or

Object.send(:private_methods)
0

精彩评论

暂无评论...
验证码 换一张
取 消