Ruby, Generate a Random Hex Color

Ruby, Generate a random hex color

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

How to generate six random hex colors and put them in a Ruby array?

You can do this which will be easier:

colors = 3.times.map{"%06x" % (rand * 0x1000000)}

NOTE: If your are using Ruby 1.9.3, you can use ranges.

colors = 3.times.map{"%06x" % rand(0..0xffffff)}

Ruby, Generate a random hex color (only light colors)

In this thread colour lumincance is described with a formula of

(0.2126*r) + (0.7152*g) + (0.0722*b)

The same formula for luminance is given in wikipedia (and it is taken from this publication). It reflects the human perception, with green being the most "intensive" and blue the least.

Therefore, you can select r, g, b until the luminance value goes above the division between light and dark (255 to 0). For example:

lum, ary = 0, []
while lum < 128
ary = (1..3).collect {rand(256)}
lum = ary[0]*0.2126 + ary[1]*0.7152 + ary[2]*0.0722
end

Another article refers to brightness, being the arithmetic mean of r, g and b. Note that brightness is even more subjective, as a given target luminance can elicit different perceptions of brightness in different contexts (in particular, the surrounding colours can affect your perception).

All in all, it depends on which colours you consider "light".

Ruby color generator

Using RGB you will have harder times avoiding gray colors, as well as colors "difficult to see" (I'm guessing on a white background)

If you need them to be random, you can use HSV values to stay away from the white, gray and black spectra. That means you set a range in the value and saturation parameters (for example, ~175 to 255) while hue can be selected freely at random.

So, this may work:

def random_bright_color(threshold = 175)
hue = rand(256 - threshold) + threshold
saturation = rand(256 - threshold) + threshold
value = rand(256)
hsv_to_rgb(hue, saturation, value)
end

where

def hsv_to_rgb(h, s, v)
if s == 0
r = g = b = (v * 2.55).round
else
h /= 60.0
s /= 100.0
v /= 100.0

i = h.floor
f = h - i
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
rgb = case i
when 0 then [v, t, p]
when 1 then [q, v, p]
when 2 then [q, v, t]
when 3 then [p, q, v]
when 4 then [t, p, v]
else [v, p, q]
end
end
rgb.map{|color| (color * 255).round}
end

is ported from here and the explanation can be found on the same Wikipedia article


However, if you additionally need to have random colors different from each other, perhaps the really true solution is to have them selected from a group of base colors, and select at random from that set.

Ruby shortest way to write rnd hex

def random_value
r = Random.new
((r.rand * 16)).to_i.to_s(16)
end

puts random_value + random_value + random_value

Or, after some quick research:

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

From Ruby, Generate a random hex color

Also, you shouldn't be looking for a more efficient solution per se. You seem to be looking for something more elegant, simple, and intuitive. (My solution is none of these, by the way. The searched one is.)

How to generate a color based on an alphanumeric string using Ruby?

You can just take a few first digits:

require 'digest/md5'
color = Digest::MD5.hexdigest('My text')[0..5]

How do I generate a random hex code that of a lighter color in javascript?

What I would do is generate a number from 00 to FF for each (RGB) (ie 000000 to FFFFFF). I would also make sure the G value is approximately higher than 33.

Secure Random hex digits only

Check out the api for SecureRandom: http://rails.rubyonrails.org/classes/ActiveSupport/SecureRandom.html

I believe you're looking for a different method: #random_number.

SecureRandom.random_number(a_big_number)

Since #hex returns a hexadecimal number, it would be unusual to ask for a random result that contained only numerical characters.

For basic use cases, it's simple enough to use #rand.

rand(9999)

Edited:

I'm not aware of a library that generates a random number of specified length, but it seems simple enough to write one. Here's my pass at it:

def rand_by_length(length)
rand((9.to_s * length).to_i).to_s.center(length, rand(9).to_s).to_i
end

The method #rand_by_length takes an integer specifying length as a param and tries to generate a random number of max digits based on the length. String#center is used to pad the missing numbers with random number characters. Worst case calls #rand for each digit of specified length. That may serve your need.

Generating pastel colors

Try this:

start_color = 128 # minimal color amount
total_offset = 64 # sum of individual color offsets above the minimal amount
'#' +
[0, rand(total_offset), rand(total_offset), total_offset].sort.each_cons(2).map{|a,b|
"%02x" % (start_color+b-a)
}.join

Actually, here's tiny Sinatra app that you can play with and see the results instantly:

require 'sinatra'

def get_pastel start_color, total_offset
'#' +
[0, rand(total_offset), rand(total_offset), total_offset].sort.each_cons(2).map{|a,b|
"%02x" % (start_color+b-a)
}.join
end

get '/:start_color/:total_offset' do |start_color, total_offset|
(0..20).map{c = get_pastel(start_color.to_i, total_offset.to_i)
"<span style='background-color:#{c}'>#{c}</span>\n"
}.join
end

Then fire up the browser and see how it looks:

http://localhost:4567/192/64

http://localhost:4567/128/128

;)



Related Topics



Leave a reply



Submit