Ruby 矩阵cycle()操作
Array#cycle() : cycle() 是一个数组类方法,它通过对数组中的每个元素每次调用给定的块来返回数组,调用次数为’n’,如果给定的是’nil’,那么它将永远调用它。
语法。Array.cycle()
参数:
block – condition
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 :