Array#collect() : collect() is an Array class method which invokes the argument block once for each element of the array. A new array is returned which has the value returned by the block.
Syntax: Array.collect() Parameter: Arrays in which we want elements to be invoked Return: array with all the envoked elements
Code #1 : Example for collect() method
# Ruby code for collect() method # declaring array a = [1, 2, 3, 4] # invoking block for each element puts "collect a : #{a.collect {|x| x + 1 }}\n\n" puts "collect a : #{a.collect {|x| x - 5*7 }}\n\n" |
chevron_right
filter_none
Output :
collect a : [2, 3, 4, 5] collect a : [-34, -33, -32, -31]
Code #2 : Example for collect() method
# Ruby code for collect() method # declaring array a = ["cat", "rat", "geeks"] # invoking block for each element puts "collect a : #{a.collect {|x| x + "!" }}\n\n" puts "collect a : #{a.collect {|x| x + "_at" }}\n\n" |
chevron_right
filter_none
Output :
collect a : ["cat!", "rat!", "geeks!"] collect a : ["cat_at", "rat_at", "geeks_at"]
Recommended Posts:
- Ruby | Array collect!() operation
- Ruby | Array any?() operation
- Ruby | Array map!() operation
- Ruby | Array dig() operation
- Ruby | Array at() operation
- Ruby | Array clear() operation
- Ruby | Array delete_if() operation
- Ruby | Array bsearch_index() operation
- Ruby | Array drop() operation
- Ruby | Array size() operation
- Ruby | Array cycle() operation
- Ruby | Array compact!() operation
- Ruby | Array delete() operation
- Ruby | Array concat() operation
- Ruby | Array delete_at() operation
- Ruby | Array count() operation
- Ruby | Array compact() operation
- Ruby | Array combination() operation
- Ruby | Array class eql?() operation
- Ruby | Array intersection operation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

