2016-08-13 43 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]