我目前正在为“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 'securerandom'
randomstring = SecureRandom.hex(n)
它将生成长度为2n的随机字符串,包含0-9和a-f
其他回答
要将您的第一句话变成一句话:
(0...8).collect { |n| value << (65 + rand(25)).chr }.join()
其他人也提到了类似的内容,但这使用了URL安全功能。
require 'securerandom'
p SecureRandom.urlsafe_base64(5) #=> "UtM7aa8"
p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
结果可能包含A-Z、A-Z、0-9、“-”和“_”。如果填充为真,则也使用“=”。
require 'securerandom'
SecureRandom.urlsafe_base64(9)
下面是一个长度为8的随机密码的简单代码:
rand_password=('0'..'z').to_a.shuffle.first(8).join
我的2美分:
def token(length=16)
chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
(0..length).map {chars.sample}.join
end