2016-08-13 41 views
1

考慮以下陣列和範圍:爲什麼一個嵌套在另一個每個循環的每個循環中蘭德不起作用

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的將是無用的。這是爲什麼?你會建議什麼解決方案?

回答

2

您是否考慮將範圍存儲在數組中,並根據需要從rand進行繪製?

friends = ["Joe", "Sam", "Tom"] 
ary =[(1..5), (6..10), (11..20)] 
year = (1..3) 
friends.each do |friend| 
    year.each do |yr| 
    p "#{friend} at the end of year #{yr} wrote #{rand(ary[yr - 1])} essays" 
    end 
end 

這就產生,例如:

"Joe at the end of year 1 wrote 5 essays" 
"Joe at the end of year 2 wrote 7 essays" 
"Joe at the end of year 3 wrote 16 essays" 
"Sam at the end of year 1 wrote 3 essays" 
"Sam at the end of year 2 wrote 7 essays" 
"Sam at the end of year 3 wrote 18 essays" 
"Tom at the end of year 1 wrote 2 essays" 
"Tom at the end of year 2 wrote 8 essays" 
"Tom at the end of year 3 wrote 15 essays" 
+0

每個循環(或任何其他解決方案)應該在每一個元素上進行迭代,從第一個到最後一個,不重複。 ary中元素的順序應該受到尊重,以便從第1年到第3年有書面散文的進展。 – Asarluhi

+1

@Asarluhi您是否嘗試過運行提供的解決方案?我尊重你在你的問題中提出的相同進展。 – pjs

+0

你是對的,我沒有注意到你從ary中刪除rand。非常感謝@pjs,它的工作原理! – Asarluhi

2

除了@pjs,您可以使用each_with_index方法

friends = ["Joe", "Sam", "Tom"] 
ary =[(1..5), (6..10), (11..20)] 
friends.each do |friend| 
    ary.each_with_index do |value, year| 
    p "#{friend} at the end of year #{year+1} wrote #{rand(value)} essays" 
    end 
end 

另外,回答你的問題:」 ..使rand方法的使用將是無用的「 - 當你創建一個數組時,其中的方法 - 這些方法的元素,他們將返回他們在這個數組中的工作結果,下一次,你可以在你的控制檯中嘗試使用irb

2.3.0 :001 > ary = [rand(1..5), rand(6..10), rand(11..20)] 
=> [2, 9, 12]