Generate Unique Random String With Letters And Numbers In Lower Case

前端 未结 11 1946
感情败类
感情败类 2020-12-23 09:45

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    
相关标签:
11条回答
  • 2020-12-23 10:20

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

    api_string = Array.new(32){rand(36).to_s(36)}.join
    
    0 讨论(0)
  • 2020-12-23 10:21

    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”

    0 讨论(0)
  • 2020-12-23 10:26

    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)
    
    0 讨论(0)
  • 2020-12-23 10:26
    CHARS = (?0..?9).to_a + (?a..?z).to_a
    api_string = 32.times.inject("") {|s, i| s << CHARS[rand(CHARS.size)]}
    
    0 讨论(0)
  • 2020-12-23 10:27

    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"
    
    0 讨论(0)
  • 2020-12-23 10:29

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

    0 讨论(0)
提交回复
热议问题