我目前正在为“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 random_string(length = 8)
  rand(32**length).to_s(32)
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
SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

来自Devise的东西

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

 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

您可以使用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