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

其他回答

此解决方案为激活代码生成一个易于读取的字符串;我不希望人们把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

在这里加上我的美分。。。

def random_string(length = 8)
  rand(32**length).to_s(32)
end

红宝石1.9+:

ALPHABET = ('a'..'z').to_a
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

10.times.map { ALPHABET.sample }.join
#=> "stkbssowre"

# or

10.times.inject('') { |s| s + ALPHABET.sample }
#=> "fdgvacnxhc"

从Ruby 2.5开始,使用SecureRandom.andlettery非常简单:

len = 8
SecureRandom.alphanumeric(len)
=> "larHSsgL"

它生成包含A-Z、A-Z和0-9的随机字符串,因此应适用于大多数用例。它们是随机安全生成的,这可能也是一个好处。


这是一个基准,用于将其与支持率最高的解决方案进行比较:

require 'benchmark'
require 'securerandom'

len = 10
n = 100_000

Benchmark.bm(12) do |x|
  x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }
  x.report('rand') do
    o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
    n.times { (0...len).map { o[rand(o.length)] }.join }
  end
end

                   user     system      total        real
SecureRandom   0.429442   0.002746   0.432188 (  0.432705)
rand           0.306650   0.000716   0.307366 (  0.307745)

因此,rand解决方案只需要SecureRandom时间的3/4。如果您生成大量字符串,这可能很重要,但如果您只是时不时地创建一些随机字符串,我会始终使用更安全的实现,因为它也更容易调用,更显式。

[*('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