我目前正在为“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}

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

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

其他回答

其他人也提到了类似的内容,但这使用了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、“-”和“_”。如果填充为真,则也使用“=”。

在ruby 1.9中,可以使用Array的choice方法,该方法返回数组中的随机元素

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

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

此解决方案为激活代码生成一个易于读取的字符串;我不希望人们把8和B混淆,把1和I混淆,把0和O混淆,把L和1混淆,等等。

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
  charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
  (0...size).map{ charset.to_a[rand(charset.size)] }.join
end

我最喜欢的是(:A..:Z).to_A.shuff[0,8].join。请注意,shuffle需要Ruby>1.9。