Ruby class question

Possible duplicate:
class <self idiom in Ruby

I have a quick Ruby question. I come from the Java / c background, so I understand in Ruby "self" when the link inside the instance method acts like "this". And I". the prefix for the method defines it as a class method.

But what does it mean here?

class << self def some_method end end 
+4
source share
4 answers

What happens here is that we again open the class of the object from the inside and define a new instance method on it. This is one of the ways you can do what is called โ€œbeheading monkeysโ€ in Ruby. This method adds the method only to the current object, and not to all objects of the class.

This is equivalent to this:

 my_obj = MyClass.new class << my_obj def some_method end end # or... def my_obj.some_method end 

Here is a good article that covers it: Learning Ruby: class <yourself .

+4
source

The syntax class << some_objct opens the class some_object singleton, which is a special "secret" class to which only this object belongs. Using the singleton class, you can define the methods that one object responds to, while other instances of its normal class do not.

So for example:

 a = "Hello world" b = "Hello world" # Note that this is a different String object class << a def first_letter self[0,1] end end puts a.first_letter # prints "H" puts b.first_letter # Raises an error because b doesn't have that method 

In the context of a class, these two method definitions are equivalent:

 class Foo def self.bar puts "Yo dawg" end end class Foo class << self def bar puts "Yo dawg" end end end 

The second form may be useful in certain circumstances (for example, when you want to declare attr_accessor for the class object itself).

+1
source

This is how you define methods for a singleton / eigen class object.

 class << foo def bar end end 

equivalently

 def foo.bar end 
0
source

If you use it as follows:

 class Foo class << self def something puts "something" end def something_else puts "something else" end end end Foo.something 

This is a shorthand for:

 class Foo def self.something puts "something" end def self.something_else puts "something else" end end 

I'm really not a fan of notation.

-1
source

All Articles