tags:

views:

508

answers:

4

How can I generate a random hex color with ruby?

+3  A: 

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, b, g = [r, b, g].map { |s| if s.size == 1 then '0' + s else s end }

color = r + b + g      # => e.g. "09f5ab"
Daniel Spiewak
This is considerably more customizable, but Jeremy's solution is much much more concise.
Benson
A: 

Generate three numbers in the range from 0 to 255 inclusive, then concatenate their 2-digit hex representations.

Carl Smotricz
Like Daniel's solution does :)
Carl Smotricz
+10  A: 

Here's one way:

colour = "%06x" % (rand * 0xffffff)
yjerem
wow! this is awesome.
Joseph Silvashy
+2  A: 

rand(0xffffff).to_s(16)

mpeg