Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, Generate a random hex color

Tags:

ruby

How can I generate a random hex color with ruby?

like image 709
JP Silvashy Avatar asked Nov 08 '09 23:11

JP Silvashy


4 Answers

Here's one way:

colour = "%06x" % (rand * 0xffffff)
like image 109
Paige Ruten Avatar answered Nov 09 '22 05:11

Paige Ruten


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)
like image 40
c-amateur Avatar answered Nov 09 '22 04:11

c-amateur


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"
like image 12
Daniel Spiewak Avatar answered Nov 09 '22 04:11

Daniel Spiewak


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*')

like image 6
airled Avatar answered Nov 09 '22 04:11

airled