Panasonic Youth rob sanheim writes about software, business, ruby, music, stuff and things



Posted
29 August 2006 @ 8pm

Tagged
Less Code, Rails, Refactoring, Ruby

Discuss

Symbol#to_proc and inconsistent code vs DRY

Jeremy recently wrote some good tips on cutting back on your code base, but his last tip is one I'm not sure about. It recommends using the Symbol#to_proc (in ActiveSupport, coming in ruby 1.9) shortcut for simple enumerable calls. Like many rubyists, I appreciate the elegance and DRYness of to_proc, as you can go from this:

RUBY:
  1. pugs.map { |pug| pug.bathe! }

to this:

RUBY:
  1. pugs.map &:bathe!

I don't like repeated the "pug" in the that first construct, but it is more obvious to newbies. But I don't think thats a huge issue - explaining to_proc isn't hard.

My main issue is you can only use to_proc for the simplest cases, so your collection methods end up looking inconsistent. Consider the following:

RUBY:
  1. pugs.select { |pug| !pug.clean? } # or
  2. pugs.map { |pug| pug.feed(diet_dog_food)

Since these calls aren't a simple property call, but involve operating on a property or passing in a parameter, you can't use to_proc. It hurts my eyes to see a model with eight collection methods, three of which using to_proc since they can, and the other five using traditional syntax. I love beautiful code, and when things get inconsistent they get ugly. Right now I'm still using both methods where appropriate, so I'm still undecided...

Further reading: possible changes to the implementation of to_proc for ruby 1.9, read only when you have some uniterrupted time to digest.


2 Comments

Posted by
Jeremy Voorhis
31 August 2006 @ 1pm

pugs.map { |pug| pug.bathe! }

is no less DRY than

pugs.map &:bathe!

Sure, we see “pug” twice in the first bit of code, but there is a difference between declaring a block variable and accessing a method on it. I put Symbol#to_proc in the same category as conditionals like “unless” and “until”; you can get the same effect with “if not” and “while not”, but the former are more succinct and do save you some typing.


Posted by
Pius Uzamere II
1 September 2006 @ 5am

I agree. As far as I can tell, Symbol#to_proc is straight up syntactic sugar — nothing more, nothing less.


Leave a Comment

Code worth Stealing From Ruby 1.8.5 - pretty_inspect Deprecation in Rails, and What You Can Do About It