How can I 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.
How can I 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"
SecureRandom.urlsafe_base64(length)8.times.map { [*'0'..'9', *'a'..'z'].sample }.join
'0'..'9' generates an array from 0 to 9, and 'a'..'z' generates an array from a to z, but what exactly does the * before each of them does?'0'..'9' is range and * is splat operator. It splits the elements of the range into single items which are returned as a group, so basically * is helping you to separate out elements so that they can be sampled out using sample methodNewer versions of Ruby support SecureRandom.base58, which will get you much denser tokens than hex, without any special characters.
> SecureRandom.base58(24)
> "Zp9N4aYvQfz3E6CmEzkadoa2"
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)
rand(36**len).to_s(36).length == len, so you will have to do rand(36**len).to_s(36).rjust(len, '0')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