我意识到我的沟通技巧并不那么出色(我甚至在尝试查找时遇到问题),所以我让代码发言:
easy_as_123 = ("a".."c").to_a
10.times do |j|
if j >= easy_as_123.length
puts "j is #{j}, letter is #{easy_as_123[j % easy_as_123.length]}"
else
puts "j is #{j}, letter is #{easy_as_123[j]}"
end
end
是否有一个更优雅,更简洁的解决方案,可以不断迭代我的[a,b,c]数组?
编辑,我发布的代码是作品,这正是我正在寻找的结果,但它不简洁也不好看,是否有方法能够以更优雅的方式实现同样的结果?
答案 0 :(得分:5)
Enumerable#cycle
是你的朋友。无限循环:
(?a..?c).cycle.with_index do |letter, j|
puts "j is #{j}, letter is #{letter}"
end
在10次迭代后打破一个循环:
(?a..?c).cycle.with_index do |letter, j|
break if j >= 10
puts "j is #{j}, letter is #{letter}"
end
使用#take
(@Stefan的信用):
(?a..?c).cycle.take(10).each.with_index do |letter, j|
puts "j is #{j}, letter is #{letter}"
end
反过来说:
enum = (?a..?c).cycle
10.times do |j|
puts "j is #{j}, letter is #{enum.next}"
end
没有#cycle
:
enum = (?a..?c).to_a
10.times do |j|
puts "j is #{j}, letter is #{enum[j % enum.length]}"
end
评论:
if
是多余的; to_a
是多余的,可能会枚举范围。答案 1 :(得分:1)
在Enumerator
的新实例中定义无限循环:
enum = Enumerator.new do |y|
j = 0
arr = ['a','b','c'].cycle
loop do
y << "j is #{j}, letter is #{arr.next}"
j += 1
end
end
enum.next #=> "j is 0, letter is a"
enum.next #=> "j is 1, letter is b"
enum.next #=> "j is 2, letter is c"
enum.next #=> "j is 3, letter is a"
想回到开头?使用Enumerator#rewind
:
enum.rewind
enum.next #=> "j is 0, letter is a"
使用take
:
puts enum.take 10 #=>
# j is 0, letter is a
# j is 1, letter is b
# j is 2, letter is c
# j is 3, letter is a
# j is 4, letter is b
# j is 5, letter is c
# j is 6, letter is a
# j is 7, letter is b
# j is 8, letter is c
# j is 9, letter is a
或使用times
和next
:
10.times { p enum.next } #=>
# "j is 0, letter is a"
# "j is 1, letter is b"
# "j is 2, letter is c"
# "j is 3, letter is a"
# "j is 4, letter is b"
# "j is 5, letter is c"
# "j is 6, letter is a"
# "j is 7, letter is b"
# "j is 8, letter is c"
# "j is 9, letter is a"