If you declare a method at top-level, it is a method of Object. For example:
irb(main):001:0> Object.instance_methods.include? 'foo'
=> false
irb(main):002:0> def foo; puts 'hello'; end
=> nil
irb(main):003:0> Object.instance_methods.include? 'foo'
=> true
irb(main):004:0> Object.new.foo
hello
=> nil
irb(main):005:0> self.foo
hello
=> nil
If you declare a variable at top-level, its scope depends on how you declare it. A local variable (e.g. foo = 'foo') should only be scoped within the current block (or, at top-level, within the top level of the script or interactive session). That means that other objects and methods won't be able to access it. Example:
irb(main):001:0> foo = 'foo'
=> "foo"
irb(main):002:0> def hi; puts foo; end
=> nil
irb(main):003:0> hi
NameError: undefined local variable or method `foo' for main:Object
from (irb):2:in `hi'
from (irb):3
If you declare it as an instance variable, it becomes an instance variable of that "main" object:
irb(main):004:0> @foo = 'foo'
=> "foo"
irb(main):005:0> p Object.new
#<Object:0x4e6f8>
=> nil
irb(main):007:0> p self.inspect
"#<Object:0x37a08 @foo=\"foo\">"
=> nil
If you declare it as a class variable, it becomes a class variable of Object:
irb(main):008:0> @@foo = 'foo'
=> "foo"
irb(main):012:0> def Object.hi; puts @@foo; end
=> nil
irb(main):013:0> Object.hi
foo
=> nil
Lastly, if you declare it global, it is of course global (any code in any class or module can access it):
irb(main):015:0> module Demo
irb(main):016:1> class Test
irb(main):017:2> def hi
irb(main):018:3> puts $foo
irb(main):019:3> end
irb(main):020:2> end
irb(main):021:1> end
=> nil
irb(main):022:0> Demo::Test.new.hi
foo
=> nil
I hope that helps to explain matters. This is exactly the behavior I would expect from the scoping rules given for Ruby.
Pacem in terris / Mir / Shanti / Salaam / Heiwa
Kevin R. Bullock
路路路
On Jun 15, 2004, at 12:28 PM, Sam Sungshik Kong wrote:
2. I heard that the top-level functions become methods of Object.
Then am I defining a class (Object)?
If I do the following
print "Hello"
what did I do? Am I in the Object class definition part or outside of
Object?
In other words, is the code <print "Hello"> part of Object?
If not, how is it related to main?
Likewise, if I declare a variable on top-level, is it part of Object?
Of course, it's a global variable.
Is a global variable outside of Object class?
If so, it's not OO...?