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

其他回答

SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

来自Devise的东西

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

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

请注意: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

试试这个

def rand_name(len=9)
  ary = [('0'..'9').to_a, ('a'..'z').to_a, ('A'..'Z').to_a]
  name = ''

  len.times do
    name << ary.choice.choice
  end
  name
end

我喜欢这条线索的答案,真的很有帮助!,但如果我可以说,它们中没有一个满足我的愿望,可能是rand()方法。我觉得这不太对,因为我们已经有了Array#choice方法。

以下内容对我很有用

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