Ruby, Generate a random hex color

Here's one way:

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

You can generate each component independently:

r = rand(255).to_s(16)
g = rand(255).to_s(16)
b = rand(255).to_s(16)

r, g, b = [r, g, b].map { |s| if s.size == 1 then '0' + s else s end }

color = r + g + b      # => e.g. "09f5ab"

SecureRandom.hex(3)
#=> "fef912"

The SecureRandom module is part of Ruby's standard library

require 'securerandom'

It's autoloaded in Rails, but if you're using Rails 3.0 or lower, you'll need to use

ActiveSupport::SecureRandom.hex(3)

Tags:

Ruby