method
collect
![Very extensive documentation Importance_5](https://d2vfyqvduarcvs.cloudfront.net/images/importance_5.png?1349367920)
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"]
Register or
log in
to add new notes.
Oleg -
April 23, 2009
shuber -
August 20, 2009
noniq -
March 18, 2010
tadman -
April 23, 2009
Artur79 -
June 25, 2010 - (v1_8_6_287 - v1_8_7_72)
![Default_avatar_30](https://www.gravatar.com/avatar/26dcc25613404cafb8a03d946ec3bcf6?size=30&default=http://apidock.com/images/default_avatar_30.png)
5 thanks
Handy shorthand for array manipulation
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"]
![Default_avatar_30](https://www.gravatar.com/avatar/0effdbe005306c5495278ebea15a7299?size=30&default=http://apidock.com/images/default_avatar_30.png)
4 thanks
Symbol#to_proc
@tadman - or simply defining:
class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } end end
![Default_avatar_30](https://www.gravatar.com/avatar/c03fdc9fc1f107225b664934e5ff5965?size=30&default=http://apidock.com/images/default_avatar_30.png)
3 thanks
collect_with_index
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
![Default_avatar_30](https://www.gravatar.com/avatar/b850a6cd0c0f8993fa152645ca9a7fbd?size=30&default=http://apidock.com/images/default_avatar_30.png)
2 thanks
Rails and Ruby 1.8.7 Extensions
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)
![Default_avatar_30](https://www.gravatar.com/avatar/e44ea56cad83e8e02bec15bfcef3f3f3?size=30&default=http://apidock.com/images/default_avatar_30.png)
0 thanks
Can operate for both key and value for Hash
If you need to process both key and value of the Hash:
>> {"a" => "aa", "b" => "bb", "c" => "cc"}.collect {|k,v| [k,k+v]} => [["a", "aaa"], ["b", "bbb"], ["c", "ccc"]]