为什么在嵌套在另一个循环中的每个循环内部rand不起作用

时间:2016-08-13 21:54:19

标签: ruby each nested-loops

考虑以下数组和范围:

friends = ["Joe", "Sam", "Tom"]
ary = [rand(1..5), rand(6..10), rand(11..20)]
range = (0..2)

我想创建一个返回Joe的代码,如下所示:

"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 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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]