2

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!

whirlwin
  • 16,044
  • 17
  • 67
  • 98

3 Answers3

5
def random_value
     r = Random.new
     ((r.rand * 16)).to_i.to_s(16)
end

puts random_value + random_value + random_value

Or, after some quick research:

"%06x" % (rand * 0xffffff)

From Ruby, Generate a random hex color

Also, you shouldn't be looking for a more efficient solution per se. You seem to be looking for something more elegant, simple, and intuitive. (My solution is none of these, by the way. The searched one is.)

Community
  • 1
  • 1
Mike
  • 19,267
  • 11
  • 56
  • 72
  • This is much sexier! Thanks! And you are probably right, a more simple solution was what I was looking for. – whirlwin Dec 27 '10 at 02:58
  • 2
    Sexier... I think that's a wonderful synonym for elegance. I'm sure it was the first thing Dijkstra blurted when he discovered the Shortest Path algorithm. – Mike Dec 27 '10 at 02:59
  • 1
    `rand` takes an integer value, allowing the command to be a bit simpler: `'%06x' % rand(0xffffff)`. – the Tin Man Dec 27 '10 at 03:51
3
# For Ruby 1.9
require 'securerandom'
SecureRandom.hex(16)

# For Ruby 1.8 and above
require 'active_support/secure_random'
ActiveSupport::SecureRandom.hex(16)
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
1

Something like this?

(rand * MAX_VALUE).to_i.to_s(16)

Where MAX_VALUE is the upper bound for the numbers. You can also add some lower bound:

(MIN_VALUE + rand * (MAX_VALUE - MIN_VALUE)).to_i.to_s(16)

This will give you numbers in the range [MIN_VALUE,MAX_VALUE)

aromero
  • 25,681
  • 6
  • 57
  • 79