Definition of method in top level

前端 未结 2 1228
野的像风
野的像风 2021-01-21 19:02

I\'m wondering about definition of method in top level.

puts RUBY_VERSION #=> 2.1.5
def greet
  \"hello, world\"
end
class Object
    greet #=> \"hello, wo         


        
2条回答
  •  一个人的身影
    2021-01-21 19:55

    Using irb, defining greet at the top-level does NOT define greet as a private method, at least using ruby 2.x:

    $ irb
    > RUBY_VERSION
    => "2.3.0"
    > def greet; "hi"; end
    => :greet
    
    > Object.methods.grep /greet/
    => [:greet]
    
    > Object.private_methods.grep /greet/
    => []
    > Object.private_instance_methods.grep /greet/
    => []
    

    In ruby, a "private method" is one that cannot be called with an explicit "receiver" in the usual way. (See e.g. this SO page.) Since self.greet and Object.greet both produce the same result as greet, it follows that greet (defined at the top-level in irb) cannot be a private method.

    The situation is different when using the ruby compiler.

提交回复
热议问题