我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
a='';8.times{a<<[*'a'..'z'].sample};p a
or
8.times.collect{[*'a'..'z'].sample}.join
其他回答
为什么不使用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
我们一直在代码中使用这个:
class String
def self.random(length=10)
('a'..'z').sort_by {rand}[0,length].join
end
end
支持的最大长度是25(无论如何,我们只在默认情况下使用它,所以这不是问题)。
有人提到“…”如果你想完全避免产生冒犯性的词语,z是次优的。我们的一个想法是去掉元音,但你最终还是会得到WTFBBQ等。
下面是另一种方法:
它使用安全随机数生成器而不是rand()可用于URL和文件名包含大写、小写字符和数字具有不包含不明确字符I0l01的选项
需要“安全”
def secure_random_string(length = 32, non_ambiguous = false)
characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
%w{I O l 0 1}.each{ |ambiguous_character|
characters.delete ambiguous_character
} if non_ambiguous
(0...length).map{
characters[ActiveSupport::SecureRandom.random_number(characters.size)]
}.join
end
require 'securerandom'
SecureRandom.urlsafe_base64(9)
以下内容对我很有用
def generate_random_password(min_length, max_length)
length = SecureRandom.random_number(max_length - min_length) + min_length
character_sets = [
('a'..'z').to_a,
('A'..'Z').to_a,
('0'..'9').to_a,
"~!@^&*()_-+=[]|:;<,>.?".split('')
]
retval = []
#
# Add one character from each set
#
character_sets.each do |character_set|
character = character_set[SecureRandom.random_number(character_set.count)]
retval.push character
end
#
# Fill the rest of the password with a random character from a random set
#
i = character_sets.count - 1
while i < length
character_set = character_sets[SecureRandom.random_number(character_sets.count)]
character = character_set[SecureRandom.random_number(character_set.count)]
retval.push character
i += 1
end
retval.shuffle.join
end