我目前正在为“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 = 8)
rand(32**length).to_s(32)
end
其他回答
我想,到目前为止,我最喜欢雷达的回答。我会这样做:
CHARS = ('a'..'z').to_a + ('A'..'Z').to_a
def rand_string(length=8)
s=''
length.times{ s << CHARS[rand(CHARS.length)] }
s
end
下面是一个长度为8的随机密码的简单代码:
rand_password=('0'..'z').to_a.shuffle.first(8).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
我使用它生成保证最大长度的随机URL友好字符串:
string_length = 8
rand(36**string_length).to_s(36)
它生成小写a-z和0-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