我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
require 'sha1'
srand
seed = "--#{rand(10000)}--#{Time.now}--"
Digest::SHA1.hexdigest(seed)[0,8]
其他回答
使用此方法,您可以传入一个很短的长度。默认设置为6。
def generate_random_string(length=6)
string = ""
chars = ("A".."Z").to_a
length.times do
string << chars[rand(chars.length-1)]
end
string
end
我喜欢使用的另一种方法:
rand(2**256).to_s(36)[0..7]
如果您真的对正确的字符串长度有疑问,请添加ljust:
rand(2**256).to_s(36).ljust(8,'a')[0..7]
require 'securerandom'
SecureRandom.urlsafe_base64(9)
我的2美分:
def token(length=16)
chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
(0..length).map {chars.sample}.join
end
[*('A'..'Z')].sample(8).join
生成随机8个字母的字符串(例如NVAYXHGR)
([*('A'..'Z'),*('0'..'9')]-%w(0 1 I O)).sample(8).join
生成随机的8个字符串(例如3PH4SWF2),不包括0/1/I/O。红宝石1.9