From: daz Date: 2004-06-19T17:23:20+09:00 Subject: Re: a newbie question about main, Object... Kevin Bullock wrote: > > This thread brought up an interesting idea in my mind. If one truly > wants to define a top-level method, perhaps you could do this: > > irb(main):001:0> class << self > irb(main):002:1> def foo; puts "singleton method of top-level Object > instance"; end > irb(main):003:1> end > => nil > irb(main):004:0> foo > singleton method of top-level Object instance > => nil > irb(main):005:0> Object.new.foo > NoMethodError: undefined method `foo' for # > from (irb):5 > > The usefulness of this depends on what you want a top-level method for. > If you want a globally accessible method, the foregoing approach > doesn't work: > > irb(main):006:0> class Demo > irb(main):007:1> def bar; foo; end > irb(main):008:1> end > => nil > irb(main):009:0> Demo.new.bar > NameError: undefined local variable or method `foo' for # > from (irb):7:in `bar' > from (irb):9 > > But then, globally accessible methods are generally frowned upon in > pure OO design. If, on the other hand, you're hacking out a quick > script to do something useful, and you want a top-level method that > only needs to be accessed at top-level, this works quite well *and* > maintains good information hiding practice. > > [...] is this an established idiom? > Not one that I've seen a lot of. This script could be useful for self-hypnosis :) def self.roo puts "*** (singleton roo) [#{self}] (#{self.class} instance) ***" super end class Object def roo puts "*** ( object roo) [#{self}] (#{self.class} instance) ***" super end end module Kernel def roo puts "*** ( kernel roo) [#{self}] (#{self.class} instance) ***" end end roo #=> *** (singleton roo) [main] (Object instance) *** #=> *** ( object roo) [main] (Object instance) *** #=> *** ( kernel roo) [main] (Object instance) *** daz