Ruby shortest way to write rnd hex

Posted by Whirlwin on Stack Overflow See other posts from Stack Overflow or by Whirlwin
Published on 2010-12-27T02:41:10Z Indexed on 2010/12/27 4:53 UTC
Read the original article Hit count: 208

Filed under:

Hi.

What I have is a method used to generate random hex values. E.g 666 or FF7

However, I don't think it looks simple/elegant at all.. What I want is to make it more simple which perhaps will make my code shorter as well, but I don't know how. That is why I need tips or hints

Here is my code so far:

def random_values
random_values = Array.new
letters = ['A','B','C','D','E','F']
for i in 1..15
  if i <= 9
    random_values << i
  else
    random_values << letters[i-10]
  end
end  
return random_values.shuffle[0].to_s + random_values.shuffle[0].to_s + random_values.shuffle[0].to_s
end

As you probably see, I do not generate random numbers. I just shuffle the array containing the values I want, meaning all the numbers in the array are unique, which is not needed, but was the easiest solution for me when I wrote the code.

I am most concerned about the return line.. If only it was possible to write like:

return 3.times { random_values.shuffle[0] }

or

return random_values.shuffle[0].to_s *3

Thanks in advance!

© Stack Overflow or respective owner

Related posts about ruby