Ruby | Array collect!() operation
Array#collect!() : collect!() is an Array class method which invokes the argument block once for each element of the array, replacing the element with 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
a = [ "cat" , "rat" , "geeks" ]
puts "collect a : #{a.collect! {|x| x + " ! " }}\n\n"
puts "collect a : #{a.collect! {|x| x + " _at " }}\n\n"
|
Output :
collect a : ["cat!", "rat!", "geeks!"]
collect a : ["cat!_at", "rat!_at", "geeks!_at"]
Code #2 : Example for collect!() method
a = [ 1 , 2 , 3 , 4 ]
puts "collect a : #{a.collect! {|x| x + 1 }}\n\n"
puts "collect a : #{a.collect! {|x| x - 5*7 }}\n\n"
|
Output :
collect! a : [2, 3, 4, 5]
collect! a : [-33, -32, -31, -30]
Last Updated :
08 Jan, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...