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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

以下内容对我很有用

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

其他回答

您可以使用Ruby Gem Facets中的String#随机。

它基本上做到了这一点:

class String
  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    characters = character_set.map { |i| i.to_a }.flatten
    characters_len = characters.length
    (0...len).map{ characters[rand(characters_len)] }.join
  end
end

以下是@Travis R答案的改进:

 def random_string(length=5)
    chars = 'abdefghjkmnpqrstuvwxyzABDEFGHJKLMNPQRSTUVWXYZ'
    numbers = '0123456789'
    random_s = ''
    (length/2).times { random_s << numbers[rand(numbers.size)] }
    (length - random_s.length).times { random_s << chars[rand(chars.size)] }
    random_s.split('').shuffle.join
  end

在@Travis R中,答案字符和数字在一起,所以有时random_string只能返回数字或字符。通过这种改进,random_string中至少有一半是字符,其余的是数字。以防万一,如果您需要一个包含数字和字符的随机字符串

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

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个字符,并且至少包含一个数字和一个特殊字符。

Array.new(n){[*“0”..“9”].sample}.join,其中n=8。

广义:Array.new(n){[*“A”..“Z”,*“0”..“9”].sample}.join等。

来自:“生成伪随机字符串A-Z,0-9”。

鉴于:

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

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

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