From: Jacob Fugal Date: 2005-04-16T04:59:14+09:00 Subject: Re: Why specify module names redundantly in Modules? On 4/15/05, Chris wrote: > > Doing my best to convert from Perl to Ruby, and mainly loving every > minute of it. > > But I have a question about Modules... Why when I declare a Module, do > I have to prefix all the routines in that module with the module name > (or routines outside the module don't see it)? I don't get that? > Isn't this kind of redundant? For instance, I can't do this: > > Module Foo > def bar > "bar" > end > end > > puts Foo.bar > > I have to do this: > > Module Foo > def Foo.bar > "bar" > end > end I know there's a reason for this, but I'll leave it to the experts to explain that. Meanwhile, let me show some alternate uses: #------------------------------------ module Foo def bar puts "bar" end end # Add bar as a singleton method of class A's metaobject. class A extend Foo end A.bar # => prints "bar" begin A.new.bar # => raises "undefined method `bar'" rescue Exception => e puts e end # Add bar as a public instance method of B. class B include Foo end B.new.bar # => prints "bar" begin B.bar # => raises "undefined method `bar'" rescue Exception => e puts e end # Add bar as a singleton method of c. Won't exist for other objects of the same class. class C end C.new.extend( Foo ).bar # => prints "bar" begin C.bar # => raises "undefined method `bar'" rescue Exception => e puts e end begin C.new.bar # => raises "undefined method `bar'" rescue Exception => e puts e end #------------------------------------ Hope that helps make things a little clearer. Jacob Fugal