Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Nov 29 ’10

The Beauty of Collect

Being from c programming background, to get an array of some property from the objects, I used to write this in Ruby:

amount_array = []

for order in account.orders
  amount_array << order.amount.some_operation
end

While a much cleaner way is to use Array#collect:

amount_array = account.orders.collect { |order| order.amount.some_operation }

This tip was submitted by zerothabhishek.

4 notes 0 comments

  1. sanemat reblogged this from rubyquicktips
  2. atm09td reblogged this from rubyquicktips
  3. zerothabhishek submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus