Hello,
I understand that everything in ruby is an object so a method defined
in a file like this in a file
def meth1
puts self
end
actually prints main.
but when I run it in the debugger mode and do main.methods. I get
'main' undefined variable..but If i do self.methods I can see the
methods but cant see the meth1 method.I thought ruby opens the 'main'
object and adds methods to that instance.
So whats happening here?
Vivek
Hello,
I understand that everything in ruby is an object so a method
defined in a file like this in a file
def meth1
puts self
end
actually prints main.
but when I run it in the debugger mode and do main.methods. I get
'main' undefined variable..
The fact that self when printed shows "main" does not mean that there is a
variable with that name. You can make anything print main:
15:57:02 [~]: ruby -e 'o=Object.new; def o.to_s() "main" end; puts o'
main
but If i do self.methods I can see the
methods but cant see the meth1 method.I thought ruby opens the 'main'
object and adds methods to that instance.
So whats happening here?
You don't get to see private methods - and methods defined on top level
are implicitely private:
15:56:46 [~]: ruby -e 'def foo() puts "x" end; self.foo()'
-e:1: private method `foo' called for main:Object (NoMethodError)
15:56:58 [~]: ruby -e 'def foo() puts "x" end; foo()'
x
15:54:57 [~]: ruby -e 'def foo() end; p self.private_methods.grep(/foo/)'
["foo"]
15:57:44 [~]: ruby -e 'def foo() end; p private_methods.grep(/foo/)'
["foo"]