From: Robert Klemme Date: 2007-03-09T07:10:06+09:00 Subject: Re: generate UUID On 08.03.2007 22:44, Aaron Smith wrote: > Anyone have a fast way of generating a verson 4 UUID? > > I have found some libraries to do this, but it seems like it could be > done in about 8 lines of code. Any faster approches? > > what about this? > > def rand_hex(l) > validChars = ("A".."F").to_a + ("0".."9").to_a > length = validChars.size > hexCode = "" > 1.upto(l) do |i| > hexCode << validChars[rand(length-1)] > end > hexCode > end > > r = > "#{rand_hex(8)}-#{rand_hex(4)}-#{rand_hex(4)}-#{rand_hex(4)}-#{rand_hex(12)}" > puts r Make validChars and length constants declared outside the method. And also, use rand(length) otherwise you never get a "9". You could also use ?A..?F and ?0..?9 - no idea whether that makes a performance diff. But I guess this one is even faster: def rand_hex_2(l) rand(1 << (l*4)).to_a(16) end Kind regards robert