method

collect

ruby latest stable - Class: Array
collect()
public

Invokes the given block once for each element of self.

Creates a new array containing the values returned by the block.

See also Enumerable#collect.

If no block is given, an Enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect { |x| x + "!" }         #=> ["a!", "b!", "c!", "d!"]
a.map.with_index { |x, i| x * i } #=> ["", "b", "cc", "ddd"]
a                                 #=> ["a", "b", "c", "d"]

4Notes

Handy shorthand for array manipulation

Oleg · Apr 23, 20095 thanks

You may write something like this: >> ['a', 'b', 'c'].collect{|letter| letter.capitalize} => ["A", "B", "C"]

But it looks so much nicer this way: >> ['a', 'b', 'c'].collect(&:capitalize) => ["A", "B", "C"]

Symbol#to_proc

shuber · Aug 19, 20094 thanks

@tadman - or simply defining:

class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } end end

collect_with_index

noniq · Mar 18, 20103 thanks

Use Object#enum_for if you need to collect with index:

require 'enumerator'

['a', 'b', 'c'].enum_for(:each_with_index).collect do |item, index| 
"#{index}: #{item}" 
end

See also: Enumerable#each_with_index

Rails and Ruby 1.8.7 Extensions

tadman · Apr 23, 20092 thanks

Note that the use of Symbol#to_proc requires either Rails or Ruby 1.8.7. Prior versions will show:

['a', 'b', 'c'].collect(&:capitalize)
 #  => TypeError: wrong argument type Symbol (expected Proc)