× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS
Christoph Wagner
Apr 13, 2015
<p>Ever seen one of these in Ruby?</p> <pre><code class="language-ruby">class Hello class &lt;&lt; self def world new("world").hello end end def initialize(who) @who = who end def hello "Hello #{@who}!" end end</code></pre> <p>What on earth is with the <code>class &lt;&lt; self</code> business? What does that do?</p> <p>That's a common question for novice Rubyist. I sure remember the first time I saw this, I was scratching my head and wondering what's going on. To be honest, while most of Ruby's syntax is very straightforward and simple to understand, this is a bit of a wrinkle.</p> <p>Fortunately, the solution is very simple: it just makes <code>world</code> a <var>class method</var>. In other words, it's just another way to write this:</p> <pre><code class="language-ruby">class Hello def self.world new("world").hello end end</code></pre> <p>"So", I hear you asking, "if both of these are equivalent, why would anyone ever use the first version, if the second is so much simpler?"</p> <p>Good question. And fortunately, there is also an easy answer. It has two parts:</p> <ol> <li>It lets you define multiple class methods inside a block</li> <li>It makes class methods visibly stand out from the other methods</li> </ol> <p>The second reason is probably the more important one: once your class gets reasonably complex, you'll be happy to have all your class methods inside a single block so that you can navigate through your code much more easily. The little <code>self</code> at the beginning of the method name can get lost on a screenful of code quite easily.</p>
comments powered by Disqus