How to create a unique six-digit alphanumeric code in Ruby

I need to create a unique six-digit alphanumeric code. To save in my database as a voucher, no: for each transaction.

+5
source share
6 answers

I used this

  require 'sha1'
  srand
  seed = "--#{rand(10000)}--#{Time.now}--"
  Digest::SHA1.hexdigest(seed)[0,6]

How to create a random string in Ruby This link was useful

+3
source

The best way is to allow the database to process identifiers (increment). But if you insist on generating them yourself, you can use a random generator to generate the code, check it against db for uniqueness. then either accept or restore

0
source

, , :

class AlnumKey

  def initialize
    @chars = ('0' .. '9').to_a + ('a' .. 'z').to_a
  end

  def to_int(key)
    i = 0
    key.each_char do |ch|
      i = i * @chars.length + @chars.index(ch)
    end
    i
  end

  def to_key(i)
    s = ""
    while i > 0 
      s += @chars[i % @chars.length]
      i /= @chars.length
    end
    s.reverse 
  end

  def next_key(last_key)
    to_key(to_int(last_key) + 1) 
  end
end

al = AlnumKey.new
puts al.next_key("ab")
puts al.next_key("1")
puts al.next_key("zz")

, -, / ..

0
source

With the following restrictions:

  • Valid only until 2038-12-24 00:40:35 UTC
  • Generated no more than once per second

you can use this simple code:

Time.now.to_i.to_s(36)
# => "lks3bn"
0
source
class IDSequence
  attr_reader :current
  def initialize(start=0,digits=6,base=36)
    @id, @chars, @base = start, digits, base
  end
  def next
    s = (@id+=1).to_s(@base)
    @current = "0"*(@chars-s.length) << s
  end
end

id = IDSequence.new
1234.times{ id.next }

puts id.current
#=> 0000ya

puts id.next
#=> 0000yb

9876543.times{ id.next }
puts id.current
#=> 05vpqq
0
source

This would increase the collision time by getting milliseconds

(Time.now.to_f*1000.0).to_i
0
source

All Articles