class << Awesomeness
What is this << for? I searched, but the results only tell me about string concatenation…
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While it’s true that
class << somethingis the syntax for a singleton class, as someone else said, it’s most often used to define class methods within a class definition. But these two usages are consistent. Here’s how.Ruby lets you add methods to any particular instance by doing this:
This adds a method
footo someinstance, not to its class but to that one particular instance. (Actually, foo is added to the instance’s “singleton class,” but that’s more or less an implementation quirk.) After the above code executes, you can send method foo to someinstance:but you can’t send foo to other instances of the same class. That’s what
<<is nominally for. But people more commonly use this feature for syntactic gymnastics like this:When this code — this class definition — executes, what is
self? It’s the classThing. Which meansclass << selfis the same as saying “add the following methods to class Thing.” That is, foo is a class method. After the above completes, you can do this:And when you think about what
<<is doing, it all makes sense. It’s a way to append to a particular instance, and in the common case, the instance being appended to is a class, so the methods within the block become class methods.In short, it’s a terse way to create class methods within a class definition block. Another way would be to do this:
Same thing. Your example is actually a syntax error, but if you understand how
<<is used with instances and the class keyword, you’ll know how to correct it.