Collections of specific attribute values


#1

All,

Let’s say I have a collection of Address ActiveRecord instances - and
let’s say that each Address has the property “zip”. What’s the best
rails/ruby idiom for retrieving a collection of these zips?

Of course I can just iterate over my Addresses and pull out the zip but,
as OCD as it sounds, I’m convinced that there’s something in the API
that’ll let me say “collection.eachProperty(‘zip’)” or something along
those lines.

Thanks for any help you can provide,
Cory W.


#2

On Wed, 2005-11-30 at 21:35 +0100, Cory W. wrote:

Thanks for any help you can provide,
Cory W.

As far as I’m aware, the easiest way to do this is:

zipcodes = Address.find(:all).map{|address| address.zip }

  • Jamie

#3

On Wed, Nov 30, 2005 at 09:35:29PM +0100, Cory W. wrote:

Let’s say I have a collection of Address ActiveRecord instances - and
let’s say that each Address has the property “zip”. What’s the best
rails/ruby idiom for retrieving a collection of these zips?

Of course I can just iterate over my Addresses and pull out the zip but,
as OCD as it sounds, I’m convinced that there’s something in the API
that’ll let me say “collection.eachProperty(‘zip’)” or something along
those lines.

In ActiveSupport’s trunk there is Symbol#to_proc. It allows you to do:

User.find(:all).map(&:first_name)
=> [“Marcel”, “Sam”, “David”, “Nicholas”, “Jeremy”, “Jamis”]

This is equivalent to the more verbose:

User.find(:all).map {|user| user.first_name}

In your case:

addresses.map(&:zip)

Word of warning: zip is a method of class Array. If you accidentally
call
that on your collection, rather than on one of the records you’ll get a
surprise.

marcel


#4

Similarly, if you have an array (here named ‘addresses’) of Address
object instances, you can get the same result:

zipcodes = addresses.map { |address| address.zip }


#5

If you accidentally call that on your collection, rather than on one of
the records you’ll get a surprise.

marcel

My first attempt was to do such a thing - you’re right - executed nicely

  • but didn’t return exactly what I was after :wink:

Everyone - thanks for the pointer. VERY helpful. I just knew there
had to be a slick construct for this. Ridiculous how Ruby always pulls
through.

Sincerely,
Cory