【发布时间】:2018-11-07 09:46:04
【问题描述】:
我计划使用SecureRandom.hex 为我的用户生成 API 密钥。
到目前为止,这里是 3 次执行的输出:
Loading development environment (Rails 5.2.1)
2.3.5 :001 > SecureRandom.hex
=> "0369e9b7c6ffa07bd8d0a263f7b4cfa6"
2.3.5 :002 > SecureRandom.hex
=> "1a8a168d7f70676451e3d59353e22693"
2.3.5 :003 > SecureRandom.hex
=> "94cc188e9e5c3abfe587510fa79993ce"
我得到重复结果的可能性有多大?
我创建的这个方法真的会避免产生重复的内容吗?
def generate_string
string = SecureRandom.hex
generate_string if Model.where(:key => string).count > 0
string
end
unique_string = generate_string
我正在使用递归,如果字符串已经存储在数据库中,它只会产生另一个。
而且,由于我没有得到重复,我可以用SecureRandom.hex 生成多少个字符串,然后才能用完组合来生成?
【问题讨论】:
标签: ruby-on-rails ruby algorithm combinations probability