Forum: Ruby methods defined in main

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Vivek (Guest)
on 2006-02-02 00:00
(Received via mailing list)
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
Robert K. (Guest)
on 2006-02-02 00:06
(Received via mailing list)
Vivek wrote:
> 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
This topic is locked and can not be replied to.