红宝石 |数组 collect() 操作
Array#collect() : collect()是一个 Array 类方法,它为数组的每个元素调用一次参数块。返回一个新数组,其中包含块返回的值。
Syntax: Array.collect()
Parameter: Arrays in which we want elements to be invoked
Return: array with all the envoked elements
代码 #1:collect() 方法的示例
# 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"
输出 :
collect a : [2, 3, 4, 5]
collect a : [-34, -33, -32, -31]
代码 #2:collect() 方法的示例
# 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"
输出 :
collect a : ["cat!", "rat!", "geeks!"]
collect a : ["cat_at", "rat_at", "geeks_at"]