Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in ruby what's the difference between self.method and a method within class << self

Tags:

ruby

class Foo

  def self.one; 1 end

  class << self
    def two; 2 end
  end

end
puts Foo.singleton_methods.inspect # => ["two", "one"]

I've been told the above methods "one" and "two" are conceptually different but I don't see how. They are both singleton methods - what's the difference in concept and also application?

like image 594
djburdick Avatar asked Apr 01 '11 01:04

djburdick


People also ask

What is self in a class method Ruby?

If that's true it means that every piece of code you write "belongs" to some object. self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup.

Why Self is used in Ruby?

self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.

What is the difference between class method and instance method in Ruby?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.


2 Answers

In application, there is no difference. In concept, the difference is subtle, but in the first case, you are operating in the current context, and defining a method on another class instance (actually, an instance method in its Eigenclass), whereas in the second case, you are entering the context of the the metaclass ("Eigenclass") of other class instance, and then defining an instance method.

Edit:

I should add that the reasons for choosing the class << self in some cases are...

  1. Cleaner syntax when defining more than a few class-methods.
  2. You can execute other kinds of code in the Eigenclass context besides just def my_method .... You can, for instance, say attr_accessor :some_attribute in that block of code.
like image 198
Steve Jorgensen Avatar answered Oct 11 '22 19:10

Steve Jorgensen


I strongly recommend you to read "Metaprogramming Ruby". This book explains about Ruby's object model, including singleton method and singleton class.

http://pragprog.com/titles/ppmetr/metaprogramming-ruby

This article also explains same topic.

http://www.contextualdevelopment.com/articles/2008/ruby-singleton

like image 32
kyanny Avatar answered Oct 11 '22 20:10

kyanny