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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

下面是另一种方法:

它使用安全随机数生成器而不是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

其他回答

a='';8.times{a<<[*'a'..'z'].sample};p a

or

8.times.collect{[*'a'..'z'].sample}.join

我只是编写了一个小gemrandom_token来为大多数用例生成随机令牌,享受~

https://github.com/sibevin/random_token

require 'securerandom'
SecureRandom.urlsafe_base64(9)

如果需要,创建空字符串或预修复:

myStr = "OID-"

使用以下代码用随机数填充字符串:

begin; n = ((rand * 43) + 47).ceil; myStr << n.chr if !(58..64).include?(n); end while(myStr.length < 12)

笔记:

(rand * 43) + 47).ceil

它将从48-91(0,1,2..Y,Z)生成随机数

!(58..64).include?(n)

它用于跳过特殊字符(因为我不想包含它们)

while(myStr.length < 12)

它将生成总共12个字符的字符串,包括前缀。

样本输出:

"OID-XZ2J32XM"

红宝石1.9+:

ALPHABET = ('a'..'z').to_a
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

10.times.map { ALPHABET.sample }.join
#=> "stkbssowre"

# or

10.times.inject('') { |s| s + ALPHABET.sample }
#=> "fdgvacnxhc"