Forum: Ruby Extend self?

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.
Donald L. (Guest)
on 2006-05-27 11:11
I am a newbie to Ruby. I've found some code in the file dependencies.rb
within Active Support:

module Dependencies
  extend self
...

I would like to ask what does 'extend self' do here? What's purpose? I
didn't found any document mentioning such 'self-extension' case.

Cheers,
Donald
Michael F. (Guest)
on 2006-05-27 11:33
(Received via mailing list)
That's quite simple, it saves you some typing :)

module A
  def a
    p 'a'
  end
end

A.a # doesn't work, because it is not written als def self.a - you
have to include the module in a class and initialize the class to
access it.

module A
  extend self
  def a
    p 'a'
  end
end

A.a
# => 'a'

voila, so now we can access the methods directly, otherwise you would
have to write

module A
  def self.a
    p 'a'
  end
  def a
    p 'a'
  end
end

or similar... makes things a bit simpler - oh, and this is no
scientific point of view of course, just wait for the multitude of
responses that will explain it in detail

 ( i count on you guys :)
Donald L. (Guest)
on 2006-05-27 12:06
Really thanks to the quick response, but it seems that the two ways of
definitions are not really equivalent. Just did an experiment.

If I say

module A
  def self.a
    p 'a'
  end
end

class C
  include A
end

> C.a
NoMethodError: undefined method `a' for C:Class

> c = C.new
> c.a
NoMethodError: undefined method `a' for #<C:0x7e478>

While if I changed the definition of module A to

module A
  extend self
  def a
    p 'a'
  end
end

...

> C.a
NoMethodError: undefined method `a' for C:Class
> c = C.new
> c.a
"a"

Anyone can explain this?

Cheers,
Donald
Florian GroÃ? (Guest)
on 2006-05-27 14:11
(Received via mailing list)
Donald Luo wrote:

>
>> C.a
> NoMethodError: undefined method `a' for C:Class
>
> Anyone can explain this?

Module functions are not transfered by include by default. You could do
this:

class C
   include A
   extend A
end
This topic is locked and can not be replied to.