Robert Klemme
3/21/2008 8:52:00 AM
On 21.03.2008 08:14, Todd Benson wrote:
> On Thu, Mar 20, 2008 at 6:14 PM, Daniel Finnie <dan@danfinnie.com> wrote:
>> You can usually use inject or collect to eliminate the a = [] line.
>> For example:
>>
>> b = %w[a b c d e]
>> a = b.collect {|i| i * 2 }
>
> Unless you have a method that doesn't return an array (i.e. something
> other than map/collect). Sometimes you have to build the array inside
> the iterator. I was just wondering if this was common practice.
Yes, that's perfectly ok. Often you can also use a variant using
#inject, like
irb(main):003:0> b = %w[a b c d e]
=> ["a", "b", "c", "d", "e"]
irb(main):004:0> b.inject([]){|ar,el| ar << el*2}
=> ["aa", "bb", "cc", "dd", "ee"]
But that would be silly in this case since there is #map / #collect.
Kind regards
robert