From: eden li Date: 2007-03-09T10:24:15+09:00 Subject: Re: generate UUID He probably meant to_s(16), not to_a(16). Anyway, rand_hex_2 won't zero-pad, so you might want to replace the to_s with a format operator: def rand_hex_3(l) "%0#{n}x" % rand(1 << n*4) end def rand_uuid [8,4,4,4,12].map {|n| rand_hex_3(n)}.join('-') end puts rand_uuid On Mar 9, 6:17 am, Aaron Smith wrote: > Robert Klemme wrote: > > On 08.03.2007 22:44, Aaron Smith wrote: > >> 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 > > def rand_hex_2(l) > rand (1 << (l*4) ).to_a(16) > end > puts rand_hex_2(9) > > ArgumentError: wrong number of arguments (1 for 0) > > -- > Posted viahttp://www.ruby-forum.com/.