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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

为什么不使用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

其他回答

我只是编写了一个小gemrandom_token来为大多数用例生成随机令牌,享受~

https://github.com/sibevin/random_token

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

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个项目,然后将其合并。

如果需要,创建空字符串或预修复:

myStr = "OID-"

使用以下代码用随机数填充字符串:

begin; n = ((rand * 43) + 47).ceil; myStr << n.chr if !(58..64).include?(n); end while(myStr.length < 12)

笔记:

(rand * 43) + 47).ceil

它将从48-91(0,1,2..Y,Z)生成随机数

!(58..64).include?(n)

它用于跳过特殊字符(因为我不想包含它们)

while(myStr.length < 12)

它将生成总共12个字符的字符串,包括前缀。

样本输出:

"OID-XZ2J32XM"
`pwgen 8 1`.chomp

以下内容对我很有用

def generate_random_password(min_length, max_length)
    length = SecureRandom.random_number(max_length - min_length) + min_length
    character_sets = [ 
      ('a'..'z').to_a,
      ('A'..'Z').to_a,
      ('0'..'9').to_a,
      "~!@^&*()_-+=[]|:;<,>.?".split('')
    ]   
    retval = []
    #   
    # Add one character from each set
    #   
    character_sets.each do |character_set|
      character = character_set[SecureRandom.random_number(character_set.count)]
      retval.push character
    end 
    #   
    # Fill the rest of the password with a random character from a random set
    #   
    i = character_sets.count - 1 
    while i < length
      character_set = character_sets[SecureRandom.random_number(character_sets.count)]
      character = character_set[SecureRandom.random_number(character_set.count)]
      retval.push character
      i += 1
    end
    retval.shuffle.join
  end