Ruby shortest/most efficient way to write rnd hex
- by Whirlwin
Hi.
What I have is a method used to generate random hex values. E.g 666 or FF7
However, I don't think it is efficient at all.. What I want is to make it more efficient 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!