methods defined in main

V

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..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
 
R

Robert Klemme

Vivek said:
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"]


KInd regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

ANN main-4.4.0 0
[ANN] main-3.0.1 0
[ANN] main-4.0.0 (for avdi) 0
Getting methods defined in the top scope 4
A way to find out when a constant gets defined? 10
[ANN] main-2.8.3 2
[ANN] main-2.6.0 0
[ANN] main-2.5.0 4

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top