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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

鉴于:

chars = [*('a'..'z'),*('0'..'9')].flatten

可以作为参数传递的单个表达式允许重复字符:

Array.new(len) { chars.sample }.join

其他回答

以下内容对我很有用

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

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

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

另一个适用于Ruby 1.8+且速度快的技巧是:

>> require "openssl"
>> OpenSSL::Random.random_bytes(20).unpack('H*').join
=> "2f3ff53dd712ba2303a573d9f9a8c1dbc1942d28"

它得到的是随机十六进制字符串。类似的方式,您应该能够生成base64字符串('M*')。

对于devicesecure_validable,您可以使用

(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join
10.times do 
  alphabet = ('a'..'z').to_a
  string += alpha[rand(alpha.length)]
end