gpt4 book ai didi

ruby - 为什么嵌套在另一个 each 循环中的 each 循环中的 rand 不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:28 24 4
gpt4 key购买 nike

考虑以下数组和范围:

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"

山姆和汤姆每年的论文数量不同。
可以使用以下代码:

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

但是这段代码会为每个 friend 返回相同数量的文章,因此方法 rand 的使用将毫无用处。这是为什么?您会建议什么解决方案?

最佳答案

您是否考虑过将范围存储在数组中,并根据需要从 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"

关于ruby - 为什么嵌套在另一个 each 循环中的 each 循环中的 rand 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com