當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Array collect!()用法及代碼示例


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]




相關用法


注:本文由純淨天空篩選整理自mayank5326大神的英文原創作品 Ruby | Array collect!() operation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。