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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

我使用它生成保证最大长度的随机URL友好字符串:

string_length = 8
rand(36**string_length).to_s(36)

它生成小写a-z和0-9的随机字符串。它不是很可定制的,但它又短又干净。

其他回答

对于devicesecure_validable,您可以使用

(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join

我认为这是简洁、清晰和易于修改的良好平衡。

characters = ('a'..'z').to_a + ('A'..'Z').to_a
# Prior to 1.9, use .choice, not .sample
(0..8).map{characters.sample}.join

易于修改

例如,包括数字:

characters = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a

十六进制大写:

characters = ('A'..'F').to_a + (0..9).to_a

对于一系列真正令人印象深刻的角色:

characters = (32..126).to_a.pack('U*').chars.to_a

为什么不使用SecureRandom?

require 'securerandom'
random_string = SecureRandom.hex

# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)

SecureRandom还具有以下方法:

基础64随机字节(_B)随机编号

参见:http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html

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

这里有一个灵活的解决方案,允许重复数据:

class String
  # generate a random string of length n using current string as the source of characters
  def random(n)
    return "" if n <= 0
    (chars * (n / length + 1)).shuffle[0..n-1].join  
  end
end

例子:

"ATCG".random(8) => "CGTGAAGA"

还可以允许某个字符更频繁地出现:

"AAAAATCG".random(10) => "CTGAAAAAGC"

说明:上面的方法接受给定字符串的字符并生成足够大的数组。然后,它将其洗牌,取出前n个项目,然后将其合并。