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
2009-11-08 23:32:39
This is considerably more customizable, but Jeremy's solution is much much more concise.
Benson
2010-03-09 07:43:05
A:
Generate three numbers in the range from 0 to 255 inclusive, then concatenate their 2-digit hex representations.
Carl Smotricz
2009-11-08 23:32:54