将 Ruby 运行为 index.cgi, [1,3,5].shuffle 总是会产生相同的结果

发布于 2024-09-07 08:43:24 字数 318 浏览 6 评论 0原文

我确实转储了 RUBY_VERSION => 的值1.8.7

每次[1,3,5].shuffle的值也是[1,3,5] 我必须在它前面添加一个 srand(Time.now.to_i) 或 srand() 以使其随机...... 我以为 srand 会自动调用?但也许不在 .cgi 环境中?

如果我使用 irb,查看 [1,3,5].shuffle,然后退出,然后重新输入 irb,每次结果都不同。

顺便说一句, ri shuffle 没有给出任何内容,并且 Array 和 Enumerable 文档没有列出 shuffle 或 shuffle!任何一个... ?

I do dump the value of RUBY_VERSION => 1.8.7

every time, the value of [1,3,5].shuffle is also [1,3,5]
i have to add a srand(Time.now.to_i) or srand() in front of it to make it random...
I thought srand is automatically called? but maybe not in a .cgi environment?

if i use irb, and look at [1,3,5].shuffle, and exit, and re-enter irb, each time the results are different.

by the way, ri shuffle didn't give anything, and the Array and Enumerable docs didn't list shuffle or shuffle! either... ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陈年往事 2024-09-14 08:43:24

由于我看不到您如何检查它是否已更改,因此我不能肯定地说,但我希望问题必须处理您如何检查它是否已更改。如果使用随机播放,则不会改变原始数组。因此,如果您检查原始数组的值而不是返回的结果,则该方法每次都会返回相同的值

RUBY_VERSION    # => "1.8.7"

a = [1,3,5]

# a does not change, because shuffle does not mutate
a.shuffle       # => [5, 1, 3]
a               # => [1, 3, 5]

# now a does change, because shuffle! does mutate
a.shuffle!  # => [5, 3, 1]
a           # => [5, 3, 1]

此外,这里是文档 http://ruby-doc.org/core-1.8.7/classes/Array.html#M000335

Since I can't see how you checked to see whether it had changed or not, I can't say for sure, but I expect the issue has to deal with how you are checking whether it has changed or not. If you use shuffle, that does not alter the original array. So if you check the value of the original array rather than the returned result, it will appear that the method is returning the same value each time

RUBY_VERSION    # => "1.8.7"

a = [1,3,5]

# a does not change, because shuffle does not mutate
a.shuffle       # => [5, 1, 3]
a               # => [1, 3, 5]

# now a does change, because shuffle! does mutate
a.shuffle!  # => [5, 3, 1]
a           # => [5, 3, 1]

Also, here are the docs http://ruby-doc.org/core-1.8.7/classes/Array.html#M000335

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文