我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
这个解决方案需要外部依赖性,但看起来比另一个更漂亮。
安装gem fakerFaker::Lorem.characters(10)#=>“ang9cbhoa8”
其他回答
在这里加上我的美分。。。
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
require 'securerandom'
SecureRandom.urlsafe_base64(9)
要将您的第一句话变成一句话:
(0...8).collect { |n| value << (65 + rand(25)).chr }.join()
试试这个
def rand_name(len=9)
ary = [('0'..'9').to_a, ('a'..'z').to_a, ('A'..'Z').to_a]
name = ''
len.times do
name << ary.choice.choice
end
name
end
我喜欢这条线索的答案,真的很有帮助!,但如果我可以说,它们中没有一个满足我的愿望,可能是rand()方法。我觉得这不太对,因为我们已经有了Array#choice方法。