我目前正在为“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}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
为什么不使用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
其他回答
以下是长度为8的随机字符串的一行简单代码:
random_string = ('0'..'z').to_a.shuffle.first(8).join
您也可以将其用于长度为8的随机密码:
random_password = ('0'..'z').to_a.shuffle.first(8).join
在这里加上我的美分。。。
def random_string(length = 8)
rand(32**length).to_s(32)
end
Array.new(n){[*“0”..“9”].sample}.join,其中n=8。
广义:Array.new(n){[*“A”..“Z”,*“0”..“9”].sample}.join等。
来自:“生成伪随机字符串A-Z,0-9”。
Array.new(8).inject(""){|r|r<<('0'..'z').to_a.shuffle[0]} # 57
(1..8).inject(""){|r|r<<('0'..'z').to_a.shuffle[0]} # 51
e="";8.times{e<<('0'..'z').to_a.shuffle[0]};e # 45
(1..8).map{('0'..'z').to_a.shuffle[0]}.join # 43
(1..8).map{rand(49..122).chr}.join # 34
我只是编写了一个小gemrandom_token来为大多数用例生成随机令牌,享受~
https://github.com/sibevin/random_token