我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
我不记得我在哪里找到了这个,但对我来说,它似乎是最好的,也是最不需要的过程:
def random_string(length=10)
chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
password = ''
length.times { password << chars[rand(chars.size)] }
password
end
其他回答
使用此方法,您可以传入一个很短的长度。默认设置为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
为什么不使用SecureRandom?
require 'securerandom'
random_string = SecureRandom.hex
# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)
SecureRandom还具有以下方法:
基础64随机字节(_B)随机编号
参见:http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html
您可以使用Ruby Gem Facets中的String#随机。
它基本上做到了这一点:
class String
def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
characters = character_set.map { |i| i.to_a }.flatten
characters_len = characters.length
(0...len).map{ characters[rand(characters_len)] }.join
end
end
对于devicesecure_validable,您可以使用
(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join
此解决方案为激活代码生成一个易于读取的字符串;我不希望人们把8和B混淆,把1和I混淆,把0和O混淆,把L和1混淆,等等。
# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
(0...size).map{ charset.to_a[rand(charset.size)] }.join
end