Asarluhi Asarluhi - 3 months ago 5
Ruby Question

Why rand inside an each loop nested in another each loop does not work

Consider the following arrays and range:

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


I would like to create a code which return for Joe something as follows:

"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"


and for Sam and Tom a different number of essays each year.

It is possible to use the following code:

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


However this code is repetitive and redundant, not considering that the size of
ary
can be greater than here. So I thought to use the following more compact code:

friends.each do |friend|
range.each do |num|
"#{friend} at the end of year #{num+1} wrote #{ary[num]} essays"
end
end


But this code would return for each friend the same number of essays, so that the use of method
rand
would be useless. Why is that? What solution would you suggest?

pjs pjs
Answer

Have you considered storing the ranges in an array, and drawing from rand on demand?

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

This produces, for example:

"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"
Comments