Chad Perrin: SOB

15 January 2010

the unnecessarily single-lined Ruby idiom

Filed under: Geek — apotheon @ 11:49

I keep seeing a one-line expression of a particular Ruby idiom. I think it ends up looking ugly and a bit difficult to grasp as it is usually written. I recently decided to see if it still works if done on multiple lines — and it does.

I most recently ran across it in two places. One was the Ruby Best Practices book (great book so far, by the way). The other was a Weblog post by John Nunemaker called Class and Instance Variables in Ruby. In the latter, he explains that this idiom can be used to create class instance variables which — unlike class variables — are per-class specific. By contrast, the scope of a class variable (not a class instance variable) extends across the class in which it is defined and its subclasses. Anyway, his example of creating a class instance variable with accessor methods looks like this (with an extra semicolon added by me for clarity):

class Polygon
  class << self; attr_accessor :sides; end
  @sides = 8
end

After playing in irb, I discovered that the fact everyone else in the world seems to want to do this in one line isn't a result of not being able to spread it across multiple lines. Considering the one-line construction in this case looks ugly as hell to me, I'd rather have written that code like this:

class Polygon
  class << self
    attr_accessor :sides
  end
  @sides = 8
end

I don't, in fact, see any reason to cram it all into one line like that. There are times when something with a clear multiline form like this probably should be done in a single line — such as when you want to create an iterator block that only contains a single line of code:

array.each {|x| puts x }

The multiline approach would of course look like this:

array.each do |x|
  puts x
end

I think that, in a case like this, the single line form is clearer. There's a distinct single line form for a block in Ruby, though. The example of the class instance variable's accessor, on the other hand, does not have a distinct form well suited to a single line. Rather, one has to just manhandle code line terminators (the semicolons) so that Ruby won't throw errors when cramming everything onto a single line — and it ends up looking cluttered, especially when there's a symbol involved with its leading colon.

Am I the only person that thinks this way — that the class instance accessor is clearer in a multiline form than strung together on a single line? Is there some benefit to doing it all in a single line that I just haven't seen?

All original content Copyright Chad Perrin: Distributed under the terms of the Open Works License