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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

下面是一个长度为8的随机密码的简单代码:

rand_password=('0'..'z').to_a.shuffle.first(8).join

其他回答

我喜欢使用的另一种方法:

 rand(2**256).to_s(36)[0..7]

如果您真的对正确的字符串长度有疑问,请添加ljust:

 rand(2**256).to_s(36).ljust(8,'a')[0..7]

如果需要指定长度的字符串,请使用:

require 'securerandom'
randomstring = SecureRandom.hex(n)

它将生成长度为2n的随机字符串,包含0-9和a-f

这是基于一些其他答案,但它增加了一点复杂性:

def random_password
  specials = ((32..47).to_a + (58..64).to_a + (91..96).to_a + (123..126).to_a).pack('U*').chars.to_a
  numbers  = (0..9).to_a
  alpha    = ('a'..'z').to_a + ('A'..'Z').to_a
  %w{i I l L 1 O o 0}.each{ |ambiguous_character| 
    alpha.delete ambiguous_character 
  }
  characters = (alpha + specials + numbers)
  password = Random.new.rand(8..18).times.map{characters.sample}
  password << specials.sample unless password.join =~ Regexp.new(Regexp.escape(specials.join))
  password << numbers.sample  unless password.join =~ Regexp.new(Regexp.escape(numbers.join))
  password.shuffle.join
end

本质上,它确保密码长度为8-20个字符,并且至少包含一个数字和一个特殊字符。

使用此方法,您可以传入一个很短的长度。默认设置为6。

def generate_random_string(length=6)
  string = ""
  chars = ("A".."Z").to_a
  length.times do
    string << chars[rand(chars.length-1)]
  end
  string
end

下面是另一种方法:

它使用安全随机数生成器而不是rand()可用于URL和文件名包含大写、小写字符和数字具有不包含不明确字符I0l01的选项

需要“安全”

def secure_random_string(length = 32, non_ambiguous = false)
  characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a

  %w{I O l 0 1}.each{ |ambiguous_character| 
    characters.delete ambiguous_character 
  } if non_ambiguous

  (0...length).map{
    characters[ActiveSupport::SecureRandom.random_number(characters.size)]
  }.join
end