开发者

Generate Unique Random String With Letters And Numbers In Lower Case

How can I 开发者_JAVA技巧fix this code so it generates unique random letters and numbers in lower case?

api_string = (0...32).map{65.+(rand(25)).chr}.join    

At the moment, it generates only letters.


If you are using ruby 1.9.2 you can use 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"


All letters and digits, that's how numbers are represented in base 36.

api_string = Array.new(32){rand(36).to_s(36)}.join


8.times.map { [*'0'..'9', *'a'..'z'].sample }.join


Newer versions of Ruby support SecureRandom.base58, which will get you much denser tokens than hex, without any special characters.

> SecureRandom.base58(24)
> "Zp9N4aYvQfz3E6CmEzkadoa2" 


Here's one way to do it:

POSSIBLE = (('A'..'Z').to_a + (0..9).to_a)
api_string = (0...32).map { |n| POSSIBLE.sample }.join

If you have Active Support available you can also do this to make an API-key-like string:

ActiveSupport::SecureRandom.hex(32)


i forgot from where, but i've read this somehow this morning

l,m = 24,36
rand(m**l).to_s(m).rjust(l,'0')

it create random number from 0 to power(36,24), then convert it to base-36 string (that is 0-9 and a-z)


CHARS = (?0..?9).to_a + (?a..?z).to_a
api_string = 32.times.inject("") {|s, i| s << CHARS[rand(CHARS.size)]}


((('a'..'z').to_a + (0..9).to_a)*3).shuffle[0,(rand(100).to_i)].join

Replace rand(100) with rand(n) where n is the maximum length of your desired string.


This will generate a lower random string from 32 to 50 characters including numbers and letters, both:

require 'string_pattern'

puts "32-50:/xN/".gen


using SecureRandom of ruby language.

require 'securerandom' randomstring = SecureRandom.hex(5)

It will generate the n*2 random string contains “0-9″ and “a-f”


you can use Time in miliseconds with redix base 36

Example: Time.now.to_f.to_s.gsub('.', '').ljust(17, '0').to_i.to_s(36) # => "4j26l5vq964"

have a look at this answer to better explaination: https://stackoverflow.com/a/72738840/7365329


Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond).to_s(36)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜