Forum: Ruby on Rails Metaclass/Singleton class question.

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.
4c70286747864c04c5c1f9b0aa380590?d=identicon&s=25 Joe Blow (joeblow)
on 2008-10-26 19:30
I understand that (class << self; self; end) returns the singelton class
of object that is calling it but why would use that instead of self <<
MyClass ...?

For example, arent these all equivalent?

class << String
  def foo
    puts "foo"
  end
end

class String
  class << self
    def foo
      puts "foo"
    end
  end
end

class String
  (class << self; self; end).module_eval do
     def foo
       puts "foo"
     end
  end
end

So why would you use the more obscure (class << self; self; end)
technique? Can someone please explain.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-10-26 20:02
(Received via mailing list)
On 26 Oct 2008, at 18:30, Joe Blow wrote:

>    puts "foo"
>
> class String
>  (class << self; self; end).module_eval do
>     def foo
>       puts "foo"
>     end
>  end
> end
>
> So why would you use the more obscure (class << self; self; end)
> technique? Can someone please explain.

if self isn't a class for example

class Object
   def meta
     (class << self; self; end)
   end
end

x = "123"
x.meta.module_eval do
   def foo
     puts "foo"
   end
end

x.foo

you could of course have just done

def x.foo
   puts "foo"
end

but sometimes you want to more than just add a method.

Fred
This topic is locked and can not be replied to.