📜  红宝石 |数组收集!()操作

📅  最后修改于: 2022-05-13 01:54:31.093000             🧑  作者: Mango

红宝石 |数组收集!()操作

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 = ["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]