考虑以下阵列和范围:为什么一个嵌套在另一个每个循环的每个循环中兰德不起作用
friends = ["Joe", "Sam", "Tom"]
ary = [rand(1..5), rand(6..10), rand(11..20)]
range = (0..2)
我想创造出返回乔东西代码如下:
"Joe at the end of year 1 wrote 2 essays"
"Joe at the end of year 2 wrote 8 essays"
"Joe at the end of year 3 wrote 16 essays"
并且Sam和Tom每年都有不同数量的散文。
它可以使用下面的代码:
friends.each do |friend|
"#{friend} at the end of year 1 wrote #{rand(1..5)} essays"
"#{friend} at the end of year 2 wrote #{rand(6..10)} essays"
"#{friend} at the end of year 3 wrote #{rand(11..20)} essays"
end
但是这个代码是重复和多余的,没有考虑到的ary
大小可以比这里更大。所以我想用下面的更紧凑的代码:
friends.each do |friend|
range.each do |num|
"#{friend} at the end of year #{num+1} wrote #{ary[num]} essays"
end
end
但这个代码将返回每个朋友的相同数量的论文,使之使用方法rand
的将是无用的。这是为什么?你会建议什么解决方案?
每个循环(或任何其他解决方案)应该在每一个元素上进行迭代,从第一个到最后一个,不重复。 ary中元素的顺序应该受到尊重,以便从第1年到第3年有书面散文的进展。 – Asarluhi
@Asarluhi您是否尝试过运行提供的解决方案?我尊重你在你的问题中提出的相同进展。 – pjs
你是对的,我没有注意到你从ary中删除rand。非常感谢@pjs,它的工作原理! – Asarluhi