Wednesday, July 20, 2011

[Rails] Re: invoke a class method on an array of objects?

On Jul 19, 3:45 pm, Walter Lee Davis <wa...@wdstudio.com> wrote:
>
> If you have an array of objects, you can use map to pass a block to  
> each member of that array, and the result will be an array holding the  
> output of that block.
>
> ['foo','bar','baz'].map{|word| word.upcase } #-> ['FOO','BAR','BAZ']
>

Random note, you can use & and a symbol to send a message to each
element in an array. So for the above example, it would be more
concise to write

['foo','bar','baz'].map(&:upcase) #-> ['FOO','BAR','BAZ']

There are obviously still many times to use the block form, but I find
a lot can be shortened to this and it makes the code more readable.

\Peter

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate