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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

对于devicesecure_validable,您可以使用

(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join

其他回答

在这里加上我的美分。。。

def random_string(length = 8)
  rand(32**length).to_s(32)
end
a='';8.times{a<<[*'a'..'z'].sample};p a

or

8.times.collect{[*'a'..'z'].sample}.join
10.times do 
  alphabet = ('a'..'z').to_a
  string += alpha[rand(alpha.length)]
end

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

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

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

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

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

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