Panasonic Youth

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] { |pug| pug.bathe! }[/ruby] to this: [ruby] &:bathe![/ruby] 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] { |pug| !pug.clean? } # or { |pug| pug.feed(diet_dog_food)[/ruby] 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.