What's New in Edge Rails: Some Handy Enumerable helpers

Posted by ryan
at 10:17 AM on Tuesday, June 27, 2006

Enumerable has received a few handy little extensions in edge Rails. The first is the ability to sum the contents of the enumerable:

orders.sum { |o| o.total * discount }

or

orders.sum(&:total)

For those interested in the implemention, it’s pretty straight forward:

def sum
  inject(0) { |sum, element| sum + yield(element) }
end

And next we have index_by which will convert an enumerable to a hash keyed on the given block. This is definitely best explained with an example. Suppose we have an array of City objects that we want to convert to a hash based on the city names:

hash = cities.index_by(&:name)
hash #=> ["New York" => <City ...>, "London" => <City ...>]

We now have a hash of cities keyed on the citys’ names.

For those that aren’t familiar with the &:symbol syntax used as a parameter to these methods – it’s just a way to form a block that says get the value of the this symbol on the passed in object.

So in the case of:

orders.sum(&:total)

what we’re really saying is:

orders.sum { |o| o.total }

It’s just a nice shortcut to access the value of a single property.

tags: rails, rubyonrails

Comments

Leave a response

  1. Nic WilliamsJune 18, 2006 @ 02:17 PM
    hash = cities.index_by(&:name)
    hash #=> ["New York" => <City ...>, "London" => <City ...>]
    That's brilliant.
  2. MatteJune 18, 2006 @ 02:17 PM
    These features are wonderfull! Every new version of Rails has something new and very usefull!
  3. IanJune 18, 2006 @ 04:46 PM
    I'm sure you'll be blogging about ActiveResource very soon, but in case you hadn't seen this post about it, check it out: http://blog.mauricecodik.com/2006/06/instant-rest-on-rails-activeresource.html Here's the changeset http://dev.rubyonrails.org/changeset/4492
  4. Ryan DaigleJune 18, 2006 @ 04:46 PM
    Thanks Ian. Yeah, I have that one queued up...