Array#collect!():collect!()是一个Array类方法,该方法为数组的每个元素调用一次参数块,并用该块返回的值替换该元素
用法: Array.collect!() 参数: Arrays in which we want elements to be invoked 返回: 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]
相关用法
- Ruby Array collect()用法及代码示例
 - Ruby Array dig()用法及代码示例
 - Ruby Array any?()用法及代码示例
 - Ruby Array map!()用法及代码示例
 - Ruby Array at()用法及代码示例
 - Ruby Array rassoc()用法及代码示例
 - Ruby Array bsearch()用法及代码示例
 - Ruby Array delete()用法及代码示例
 - Ruby Array clear()用法及代码示例
 - Ruby Array delete_if()用法及代码示例
 - Ruby Array bsearch_index()用法及代码示例
 - Ruby Array concat()用法及代码示例
 - Ruby Array compact!()用法及代码示例
 - Ruby Array compact()用法及代码示例
 - Ruby Array delete_at()用法及代码示例
 
注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array collect!() operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
