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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

以下内容对我很有用

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

其他回答

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

我最近做了类似的事情,从62个字符中生成一个8字节的随机字符串。字符为0-9、a-z、a-z。我有一个它们的数组,循环8次,从数组中选择一个随机值。这是在Rails应用程序中。

str = ''
8.times {|i| str << ARRAY_OF_POSSIBLE_VALUES[rand(SIZE_OF_ARRAY_OF_POSSIBLE_VALUES)] }

奇怪的是,我有很多重复。现在,随机地说,这几乎永远不会发生。62^8是巨大的,但在数据库中的1200个左右的代码中,我有很多重复的。我注意到它们发生在彼此的时间边界上。换言之,我可能会在12:12:23和2:12:22看到一个二人组或类似的。。。不确定时间是不是问题。

此代码在创建ActiveRecord对象之前。在创建记录之前,此代码将运行并生成“唯一”代码。DB中的条目总是可靠地生成,但是代码(上面一行中的str)被重复得太频繁了。

我创建了一个脚本,以很小的延迟运行上述行的100000次迭代,因此需要3-4个小时才能看到每小时一次的重复模式,但一无所获。我不知道为什么我的Rails应用程序会出现这种情况。

如果您使用的是UNIX,并且仍然必须使用Ruby 1.8(没有SecureRandom)而不使用Rails,那么您也可以使用这个:

random_string = `openssl rand -base64 24`

请注意,这会生成新的shell,这非常慢,只能推荐用于脚本。

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

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

我不记得我在哪里找到了这个,但对我来说,它似乎是最好的,也是最不需要的过程:

def random_string(length=10)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
  password = ''
  length.times { password << chars[rand(chars.size)] }
  password
end