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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

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

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

其他回答

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

如果您使用的是UNIX,并且仍然必须使用Ruby 1.8(没有SecureRandom)而不使用Rails,那么您也可以使用这个:

random_string = `openssl rand -base64 24`

请注意,这会生成新的shell,这非常慢,只能推荐用于脚本。

以下是长度为8的随机字符串的一行简单代码:

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

您也可以将其用于长度为8的随机密码:

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

为什么不使用SecureRandom?

require 'securerandom'
random_string = SecureRandom.hex

# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)

SecureRandom还具有以下方法:

基础64随机字节(_B)随机编号

参见:http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html

require 'securerandom'
SecureRandom.urlsafe_base64(9)