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?
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.
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.
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.
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...
def my_method ...
. You can, for instance, say attr_accessor :some_attribute
in that block of code.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With