How can I generate a random hex color with ruby?
Asked
Active
Viewed 2.0k times
5 Answers
149
Here's one way:
colour = "%06x" % (rand * 0xffffff)

Paige Ruten
- 172,675
- 36
- 177
- 197
-
1Could someone explain it (especially the "%06x"? – Dorian Jan 17 '12 at 05:12
-
9The [% method](http://ruby-doc.org/core-1.9.3/String.html#method-i-25) on String uses the string as a format specification for the argument. "%06x" means: format a number as hex, 6 characters (digits in this case) wide, 0 padded. – Tim Gage Mar 03 '12 at 16:37
-
@jeremy-ruten, I had to move the accepted answer over to airled's answer, please fogive me ;) – JP Silvashy Oct 22 '18 at 17:07
40
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)
-
1If you are going to use this option, you will need to prepend the hex with "#". Works great, just don't forget the hash symbol at the beginning. – Eli Duke Jan 25 '18 at 07:25
12
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"

n1313
- 20,555
- 7
- 31
- 46

Daniel Spiewak
- 54,515
- 14
- 108
- 120
-
1This is considerably more customizable, but Jeremy's solution is much much more concise. – Benson Mar 09 '10 at 07:43
-
For arbitrary byte length (replace 3 w/ number of bytes): `"".tap {|s| 3.times {s << ("%02x" % rand(255))}}` – Abe Voelker Mar 28 '12 at 19:40
-
-
You should change to `rand(256)`, since this current method will limit the lightest color to `#fefefe` (highest value `rand(255)` can output is 254). – siannopollo May 27 '18 at 19:55
7
One-liner with unpack
:
Random.new.bytes(3).unpack("H*")[0]
Since ruby 2.6.0 you can do it even shorter:
Random.bytes(3).unpack1('H*')

airled
- 177
- 3
- 15
2
also you can do this:
colour = '#%X%X%X' % 3.times.map{ rand(255) }
some updates:
or if you want to freeze any color:
class RandomColor
def self.get_random
rand(255)
end
def self.color_hex(options = {})
default = { red: get_random, green: get_random, blue: get_random }
options = default.merge(options)
'#%X%X%X' % options.values
end
end
then
# full random colour
RandomColor.color_hex() => #299D3D
RandomColor.color_hex() => #C0E92D
# freeze any colour
RandomColor.color_hex(red: 100) => #644BD6
RandomColor.color_hex(red: 100) => #6488D9

nilid
- 372
- 2
- 12