The Artima Developer Community
Sponsored Link

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

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
rwdaigle

Posts: 312
Nickname: rwdaigle
Registered: Feb, 2003

Ryan is a passionate ruby developer with a strong Java background.
What's New in Edge Rails: Some Handy Enumerable helpers Posted: Jun 27, 2006 1:47 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by rwdaigle.
Original Post: What's New in Edge Rails: Some Handy Enumerable helpers
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by rwdaigle
Latest Posts From Ryan's Scraps

Advertisement

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

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

Topic: Migrations at RailsConf Previous Topic   Next Topic Topic: Echando código: ¿Monitoreando servicios RPC usando Java, ONC RPC y el protocolo Jabber? (II)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use