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 Wilkerson
--
Posted via http://www.ruby-forum.com/.
On Wed, 2005-11-30 at 21:35 +0100, Cory Wilkerson wrote:> 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 Wilkerson >As far as I''m aware, the easiest way to do this is: zipcodes = Address.find(:all).map{|address| address.zip } - Jamie
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 }
--
Posted via http://www.ruby-forum.com/.
On Wed, Nov 30, 2005 at 09:35:29PM +0100, Cory Wilkerson 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 -- Marcel Molina Jr. <marcel-WRrfy3IlpWYdnm+yROfE0A@public.gmane.org>
> If you accidentally call that on your collection, rather than on one of > the records you''ll get a surprise. > > marcelMy first attempt was to do such a thing - you''re right - executed nicely - but didn''t return exactly what I was after ;) 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 -- Posted via http://www.ruby-forum.com/.