Ruby 用小写字母和数字生成唯一的随机字符串
如何修复此代码,使其以小写形式生成唯一的随机字母和数字Ruby 用小写字母和数字生成唯一的随机字符串,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,如何修复此代码,使其以小写形式生成唯一的随机字母和数字 api_string = (0...32).map{65.+(rand(25)).chr}.join 目前,它只生成字母。CHARS=(?0..?9).to_a+(?a..?z).to_a CHARS = (?0..?9).to_a + (?a..?z).to_a api_string = 32.times.inject("") {|s, i| s << CHARS[rand(CHARS.size)]} api|u
api_string = (0...32).map{65.+(rand(25)).chr}.join
目前,它只生成字母。CHARS=(?0..?9).to_a+(?a..?z).to_a
CHARS = (?0..?9).to_a + (?a..?z).to_a
api_string = 32.times.inject("") {|s, i| s << CHARS[rand(CHARS.size)]}
api|u string=32.times.injection(“”{| s,i | s这里有一种方法:
POSSIBLE = (('A'..'Z').to_a + (0..9).to_a)
api_string = (0...32).map { |n| POSSIBLE.sample }.join
如果您有可用的活动支持,您也可以这样做以生成类似字符串的API键:
ActiveSupport::SecureRandom.hex(32)
如果您使用的是ruby 1.9.2,则可以使用SecureRandom:
irb(main):001:0> require 'securerandom'
=> true
irb(main):002:0> SecureRandom.hex(13)
=> "5bbf194bcf8740ae8c9ce49e97"
irb(main):003:0> SecureRandom.hex(15)
=> "d2413503a9618bacfdb1745eafdb0f"
irb(main):004:0> SecureRandom.hex(32)
=> "432e0a359bbf3669e6da610d57ea5d0cd9e2fceb93e7f7989305d89e31073690"
所有字母和数字,以36为基数表示数字
api_string = Array.new(32){rand(36).to_s(36)}.join
我忘了是从哪里来的,但我今天早上不知怎么读到的
l,m = 24,36
rand(m**l).to_s(m).rjust(l,'0')
它创建从0到幂(36,24)的随机数,然后将其转换为base-36字符串(即0-9和a-z)
将rand(100)
替换为rand(n)
,其中n
是所需字符串的最大长度。使用ruby语言的SecureRandom
require 'securerandom' randomstring = SecureRandom.hex(5)
它将生成n*2随机字符串,其中包含“0-9”和“a-f”8.times.map{[*'0''9',*'a''z'].sample}。join
这将生成一个32到50个字符(包括数字和字母)的较低随机字符串:
Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond).to_s(36)
require 'string_pattern'
puts "32-50:/xN/".gen
更新版本的Ruby支持,这将使您获得比十六进制更密集的令牌,而不需要任何特殊字符
> SecureRandom.base58(24)
> "Zp9N4aYvQfz3E6CmEzkadoa2"
数字的范围是48到57。这些必须包括在你的范围内。谢谢你的回答。你能举个例子让我把它标记为正确吗?对于简单的需要,这可能是很方便的,但是alpha范围只是a-f,所以生成的字符串的安全性/复杂度没有可能高。最好使用base64,它也是内置:SecureRandom.base64(16).gsub(/=+$/,'')不是API密钥的问题,但是还有一个方便的urlsafe\u base64方法:SecureRandom.urlsafe\u base64(16)=>“XpMnLfc3FySd-C4V2Ipxag”为什么使用base64更好SecureRandom.urlsafe\u base64(长度)
这比steenslag快,除了rand(36**len).to_s(36).length==len
,所以您必须执行rand(36**len).to_s(36).rjust(len,'0')这并不总是正确的
'0'..'9'
生成从0到9的数组,'a'..'z'
生成从a到z的数组,但在每个数组之前,*究竟是什么?'0'..'9'
是范围,*
是splat运算符。它将范围中的元素拆分为单个项,这些项作为一个组返回,因此基本上*
帮助您分离元素,以便使用sample
method对元素进行采样。这个答案比公认的答案要好得多。
> SecureRandom.base58(24)
> "Zp9N4aYvQfz3E6CmEzkadoa2"