2

I've just completed Ruby koan 248 and toward the end of the about_class_methods,rb file there's this section of code:

class Dog
    def self.class_method2
      :another_way_to_write_class_methods
    end
  end

  def test_you_can_use_self_instead_of_an_explicit_reference_to_dog
    assert_equal :another_way_to_write_class_methods, Dog.class_method2
  end

  # ------------------------------------------------------------------

  class Dog
    class << self
      def another_class_method
        :still_another_way
      end
    end
  end

  def test_heres_still_another_way_to_write_class_methods
    assert_equal :still_another_way, Dog.another_class_method
  end

  # THINK ABOUT IT:
  #
  # The two major ways to write class methods are:
  #   class Demo
  #     def self.method
  #     end
  #
  #     class << self
  #       def class_methods
  #       end
  #     end
  #   end
  #
  # Which do you prefer and why?
  # Are there times you might prefer one over the other?

I'm not sure I appreciate why I might, in different circumstances, prefer one syntax over the other. I can see that you might be able to define a set of methods in the class << self section, but is THAT the point being made? I assume there's something subtle I'm missing, but I don't know what that is.

Would anyone mind spelling it out to me?

moosefetcher
  • 1,841
  • 2
  • 23
  • 39
  • Here's a great answer on the topic http://stackoverflow.com/a/2505077/3109182 – Anthony Jan 13 '15 at 12:40
  • OK, I've read that and I get that `class << self` can be used to add static methods to a class. I don't see how that clears up the above question though - why should I prefer one syntax over another at times? Sorry, but I can either ask for a clearer explanation or hope that it's just not an important distinction and move on. – moosefetcher Jan 13 '15 at 13:08
  • How would you ask Ruby to generate an attribute reader for an instance variable of the class? – Jörg W Mittag Jan 13 '15 at 14:13
  • I honestly don't know. I'm guessing with one syntax you can and the other you can't? Let me know if that's what you're implying. Thanks. – moosefetcher Jan 13 '15 at 14:30

1 Answers1

0

You might want to use class << self over def self.method because you might want to add an attribute reader property to the class. In fact, any time you want to use syntax defined for classes, you might want to consider class << self. I'm new to Ruby, but I imagine if you wanted to define many class methods you could group them all together using the class << self syntax.

Garrison
  • 386
  • 2
  • 8