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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

在ruby 1.9中,可以使用Array的choice方法,该方法返回数组中的随机元素

其他回答

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

def random_string(length = 8)
  rand(32**length).to_s(32)
end

红宝石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"

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

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

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

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

这几乎是丑陋的,但也许是朝着正确的方向迈出的一步?

 (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join

下面是一个长度为8的随机密码的简单代码:

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