25/08/2009

Random hex string generator in ruby

I was looking around for a random hex string generator (pseudo random is fine for me too) and I wasn't too happy with what I found (source : http://snippets.dzone.com/posts/show/491 ):

def newpass( len )
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    return newpass
end

I tried to come up with something more to my liking, on my own but didn't fare that much better:

def rand_hexstring(length=8)
  (1..length).inject("") {|x,i|
    x+=((rand()*128)).to_i.chr
  }.unpack("H*").to_s.slice 0..length
end

I had thought of filtering it at some point and came up on a blog ( http://www.rubyrailways.com/rubys-most-underused-keyword/ ) with the following :

  (0..9).map{rand(?z).chr[/[^_\W]/]||redo}*"" 

While in the end I had no use for filtering, and shed the nice redo trick, it made me realize I could improve on my answer by using map instead of inject :

  def rand_hexstring(length=8)
    ((0..length).map{rand(256).chr}*"").unpack("H*")[0][0,length]
  end

What this does is : for each element of the range ( map ), create a one char string ( rand(256).chr ) join the resulting array ( *"" ) unpack it to hexes, get the only element ( [0] ) of the resulting array and slice it to the requested length

Aucun commentaire: