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


Ruby Array cycle()用法及代碼示例


Array#cycle():cycle()是一種Array類方法,該方法通過每次為數組“ n”中的每個元素調用給定的塊來返回數組。有時,如果給出“ nil”,它將永遠被稱為。

用法: Array.cycle()

參數:
塊狀
n-調用塊的次​​數


返回:每次為數組“ n”中的每個元素調用給定的塊。時代

代碼#1:cycle()方法示例

# Ruby code for cycle() method 
  
# declaring array 
a = [18, 22, 33, 5, 6] 
  
# declaring array 
b = [1, 4, 1, 1, 88, 9] 
  
# declaring array 
c = [18, 22, nil, nil, 50, 6] 
  
# cycling the array elements 
puts "cycle:#{a.cycle(3){ |x| puts x*x }}\n\n"
  
# cycling the array elements 
puts "cycle:#{b.cycle(2){|x| puts x}}\n\n"

輸出:

324
484
1089
25
36
324
484
1089
25
36
324
484
1089
25
36
cycle:

1
4
1
1
88
9
1
4
1
1
88
9
cycle:

代碼2:cycle()方法示例

# Ruby code for cycle() method 
  
# declaring array 
a = ["abc", "nil", "dog"] 
  
# declaring array 
b = ["cow", "1", "dog"] 
  
# cycling the array elements 
puts "cycle:#{a.cycle(3){ |x| puts x }}\n\n"
  
# cycling the array elements 
# passing negative value for cycle 
puts "cycle:#{b.cycle(-1){|x| puts x}}\n\n"

輸出:

abc
nil
dog
abc
nil
dog
abc
nil
dog
cycle:

cycle:


相關用法


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