考慮以下陣列和範圍:爲什麼一個嵌套在另一個每個循環的每個循環中蘭德不起作用
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