📜  红宝石 |数组循环()操作

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

红宝石 |数组循环()操作

Array#cycle() :cycle()是一个 Array 类方法,它通过每次调用给定块来为数组“n”号中的每个元素返回数组。次数,如果给出“nil”,那么它将永远调用它。

代码 #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 :