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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

`pwgen 8 1`.chomp

其他回答

require 'securerandom'
SecureRandom.urlsafe_base64(9)
[*('A'..'Z')].sample(8).join

生成随机8个字母的字符串(例如NVAYXHGR)

([*('A'..'Z'),*('0'..'9')]-%w(0 1 I O)).sample(8).join

生成随机的8个字符串(例如3PH4SWF2),不包括0/1/I/O。红宝石1.9

要将您的第一句话变成一句话:

(0...8).collect { |n| value  << (65 + rand(25)).chr }.join()

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

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

请注意:rand对于攻击者来说是可预测的,因此可能不安全。如果这是用于生成密码的,则绝对应该使用SecureRandom。我用的是这样的东西:

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

password = SecureRandom.random_bytes(length).each_char.map do |char|
  characters[(char.ord % characters.length)]
end.join