Ruby 数组collect!()操作
Array#collect!() : collect!()是一个数组类方法,对数组中的每个元素调用一次参数块,用该块返回的值替换该元素
语法。 Array.collect!()
参数。 我们希望元素被调用的数组
返回:包含所有被调用元素的数组
代码#1:collect!()方法的例子
# Ruby code for collect!() method
# declaring array
a = ["cat", "rat", "geeks"]
# invoking block for each element
# returning elements that don't follow
puts "collect a : #{a.collect! {|x| x + "!" }}\n\n"
puts "collect a : #{a.collect! {|x| x + "_at" }}\n\n"
输出:
collect a : ["cat!", "rat!", "geeks!"]
collect a : ["cat!_at", "rat!_at", "geeks!_at"]
代码#2:collect!()方法的例子
# Ruby code for collect!() method
# declaring array
a = [1, 2, 3, 4]
# invoking block for each element
# returning elements that don't follow
puts "collect a : #{a.collect! {|x| x + 1 }}\n\n"
puts "collect a : #{a.collect! {|x| x - 5*7 }}\n\n"
输出:
collect! a : [2, 3, 4, 5]
collect! a : [-33, -32, -31, -30]