4

I'm going through the Ruby Koans Ruby Koans and I'm at a place in "about_class_methods.rb" where there is a discussion of setting up class methods, and the Koans talk about three ways.

The two major ways to write class methods are:

1:

class Demo (define/open class)
  def self.method
end

2:

  class << self
    def class_methods
    end
  end

The koans also talk about a third method, I've never seen (that I remember):

def Demo.class_method_third_way
end

Q1 This third way is actually clearer to me than any other. Is there a reason I don't understand about why no one uses it?

Q2 Why am I wrong in thinking the syntax for 2 should be "self << def name end"? That is "Why is the syntax the way it is?" Does the class Object hold a reference to all Classes and this sticks in the method for the self class?

As always, thanks for your help and patience!

2 Answers 2

6

In (early) development classes get renamed as insight grows (not Person but Employee, not Job but one or more Roles etc.) This renaming is prone to errors if the class name is hardcoded in the class itself.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, interesting insight Steenslag!
This answer is particularly good given the OP is asking about ruby koans. :) It's a very zen-like answer.
3

In class body, self refers exactly the class object being defined. That's why def self.some_method works the same as def Demo.some_method.

class Demo
  puts self.object_id == Demo.object_id
end
#=> true

class << some_obj is the syntax to access the singleton class of some_obj. Refer to the Ruby doc:

The singleton class (also known as the metaclass or eigenclass) of an object is a class that holds methods for only that instance. You can access the singleton class of an object using class << object ... Most frequently you’ll see the singleton class accessed like this:

class C
  class << self
    # ...
  end
  # or
  class << C
  end
end

2 Comments

Thanks Arie. I read the link. I'm too much of a noob to have it help that much. I also found this: devalot.com/articles/2008/09/ruby-singleton which covers some of the same ground. In answer to my Q1, I think you're not commenting (which is fine) and in answer to Q2, I think you're expanding on the singleton concept. That said, why isn't Demo.class_method used more often? Is there something I'm missing?
@codenoob If you're using class << self; end, when you refactor your class name, you don't need to modify the name in this statement block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.