Ruby, Generate a random hex color

Ruby

Ruby Problem Overview


How can I generate a random hex color with ruby?

Ruby Solutions


Solution 1 - Ruby

Here's one way:

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

Solution 2 - Ruby

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)

Solution 3 - Ruby

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"

Solution 4 - Ruby

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

Solution 5 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJP SilvashyView Question on Stackoverflow
Solution 1 - RubyPaige RutenView Answer on Stackoverflow
Solution 2 - Rubyc-amateurView Answer on Stackoverflow
Solution 3 - RubyDaniel SpiewakView Answer on Stackoverflow
Solution 4 - RubyairledView Answer on Stackoverflow
Solution 5 - RubynilidView Answer on Stackoverflow