Ruby Daisy-Chaining for Fun & Profit

Posted on October 10, 2007

One of the things I love about Ruby is the ability to easily daisy-chain several functions together. This feature is by no means unique to Ruby, but here I’ll show how one might do this the Ruby way.

You have an array representing days of the week, indexed by 0 – 7, that you get back from a web post as strings.

days = params[:days] # {"5" => "1", "6" => "1", "2" => "1"}

But we want the keys as an array of integers in sorted order.

One way would be:

keys = days.keys
sorted = keys.sort
ints = []
sorted.each { |i| ints << i.to_i }

Of course you wouldn’t actually ever do it this way once you’re familiar with Ruby idioms and are comfortable reading daisy-chained code (it can get ugly if abused!).

In Ruby, the above four lines can be condensed into the following one-liner:

ints = days.keys.sort.map(&:to_i)

Note: Rails monkeypatches collect/map to allow for the map(&:to_i) shortcut.