我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
这里有一个灵活的解决方案,允许重复数据:
class String
# generate a random string of length n using current string as the source of characters
def random(n)
return "" if n <= 0
(chars * (n / length + 1)).shuffle[0..n-1].join
end
end
例子:
"ATCG".random(8) => "CGTGAAGA"
还可以允许某个字符更频繁地出现:
"AAAAATCG".random(10) => "CTGAAAAAGC"
说明:上面的方法接受给定字符串的字符并生成足够大的数组。然后,它将其洗牌,取出前n个项目,然后将其合并。
其他回答
我认为这是简洁、清晰和易于修改的良好平衡。
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
如果需要,创建空字符串或预修复:
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"
试试这个
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方法。
在ruby 1.9中,可以使用Array的choice方法,该方法返回数组中的随机元素
如果需要指定长度的字符串,请使用:
require 'securerandom'
randomstring = SecureRandom.hex(n)
它将生成长度为2n的随机字符串,包含0-9和a-f