我目前正在为“A”生成一个8字符伪随机大写字符串。。“Z”:

value = ""; 8.times{value  << (65 + rand(25)).chr}

但它看起来不干净,而且不能作为参数传递,因为它不是一个单独的语句。要获取混合大小写字符串“a”。。“z”加“A”。。“Z”,我将其更改为:

value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

Array.new(8).inject(""){|r|r<<('0'..'z').to_a.shuffle[0]}  # 57
(1..8).inject(""){|r|r<<('0'..'z').to_a.shuffle[0]}        # 51
e="";8.times{e<<('0'..'z').to_a.shuffle[0]};e              # 45
(1..8).map{('0'..'z').to_a.shuffle[0]}.join                # 43
(1..8).map{rand(49..122).chr}.join                         # 34

其他回答

使用“SafeRandom”Gem GithubLink

它将提供生成Rails2、Rails3、Rails4和Rails5兼容的随机值的最简单方法。

我喜欢使用的另一种方法:

 rand(2**256).to_s(36)[0..7]

如果您真的对正确的字符串长度有疑问,请添加ljust:

 rand(2**256).to_s(36).ljust(8,'a')[0..7]

这几乎是丑陋的,但也许是朝着正确的方向迈出的一步?

 (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join

其他人也提到了类似的内容,但这使用了URL安全功能。

require 'securerandom'
p SecureRandom.urlsafe_base64(5) #=> "UtM7aa8"
p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="

结果可能包含A-Z、A-Z、0-9、“-”和“_”。如果填充为真,则也使用“=”。

require 'sha1'
srand
seed = "--#{rand(10000)}--#{Time.now}--"
Digest::SHA1.hexdigest(seed)[0,8]