ruby-on-rails - rails : random unique array of fixed length

标签 ruby-on-rails ruby ruby-on-rails-5

如何确保此数组的唯一性,同时将其长度保持在 5

def fixed
  5.times.collect { SecureRandom.random_number(10) }
end

这种行为看起来奇怪:

5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 2, 3, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 3]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 3, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 4]
5.times.collect.uniq { SecureRandom.random_number(10) }
# => [0, 1, 2, 3]

最佳答案

当可能值的数量很小时——比如你的例子中的 10——然后我会生成一个包含所有选项的数组,然后随机选择一个 sample。条目数:

(0..9).to_a.sample(5)

如果可能值的数量很大,那么首先生成所有值当然不是一种选择。然后只要数组不包含足够的条目,我就会生成一个随机值:

require 'set'
values = Set.new
until values.length == 5 do
  values.add(SecureRandom.random_number(1_000_000))
end
values.to_a

请注意我使用的是 Set以确保第二个版本中值的唯一性。

关于ruby-on-rails - rails : random unique array of fixed length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822273/

相关文章:

ruby-on-rails - 'EOFError : end of file reached' on HEROKU while posting UTF-8 via SSL

ruby-on-rails - Puma Rails 5 binding.pry 仅在超时前 60 秒可用

ruby-on-rails - Rails 5 ActionCable WebSockets 未返回状态为 101 升级响应的升级 header

environment-variables - Rails 5.1 加密的 secret RAILS_MASTER_KEY env 变量未被读取

ruby-on-rails - Rails 3.1 - 嵌入 flash.swf 文件 - 最佳实践?

ruby-on-rails - rails : Is there any way to build dynamic role based authorization in rails?

ruby-on-rails - 强制 HTTP 响应在 Rails 中返回状态 200

ruby-on-rails - 在部署我的 Rails 应用程序之前,我应该检查哪些安全措施?

ruby - 配置 Mongoid 关系以返回排序的对象

ruby - 与 Ruby 中 IRB 的方法调用混淆