我需要生成一个唯一的六位字母数字代码。在我的数据库中保存为凭证号:对于每笔交易。
5522 次
6 回答
3
我用这个
require 'sha1'
srand
seed = "--#{rand(10000)}--#{Time.now}--"
Digest::SHA1.hexdigest(seed)[0,6]
如何在 Ruby 中生成随机字符串 这个链接很有用
于 2011-05-06T11:18:02.697 回答
0
我会使用数据库来生成唯一的密钥,但如果你坚持用艰难的方式来做:
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")
当然,您必须将当前密钥存储在某处,这绝不是线程/多会话安全等。
于 2011-05-06T11:01:35.587 回答
0
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
于 2011-05-06T17:08:43.300 回答
0
更好的方法是让数据库处理 ids(递增)。但是如果你坚持自己生成它们,你可以使用随机生成器生成代码,检查它与 db 的唯一性。然后要么接受要么重新生成
于 2011-05-06T10:58:26.840 回答
0
这将通过获得毫秒来缓解时间冲突问题
(Time.now.to_f*1000.0).to_i
于 2012-03-10T08:08:06.583 回答
0
具有以下限制:
- 仅在 2038-12-24 00:40:35 UTC 之前有效
- 在一秒钟内生成不超过一次
你可以使用这个简单的代码:
Time.now.to_i.to_s(36)
# => "lks3bn"
于 2011-05-06T14:46:04.127 回答