Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a series of unique HEX colors in Ruby

1 Answer

0 votes
require "securerandom"

# Generates a single random color channel (0..255)
def random_channel
  # SecureRandom.random_number(max) returns 0...max
  SecureRandom.random_number(256)
end

# Builds a full random HEX color, e.g. "#a3f09c"
def random_hex_color
  r = random_channel
  g = random_channel
  b = random_channel

  # Format each channel as two-digit hex
  format("#%02x%02x%02x", r, g, b)
end

# Generates N unique random HEX colors
def generate_random_unique_hex_colors(count)
  colors = Set.new

  # Keep generating until we have the desired number
  while colors.size < count
    colors << random_hex_color
  end

  colors.to_a
end

# Example usage
require "set"

colors = generate_random_unique_hex_colors(12)

puts "Generated HEX colors:"
colors.each { |c| puts c }


# run:
#
# Generated HEX colors:
# #7680ca
# #e2af82
# #e2eaa0
# #14c8c7
# #1903e1
# #fa9a8c
# #63bc26
# #bbdbb8
# #1d674d
# #0f61e4
# #d374db
# #b052d2
# 

 



answered 5 hours ago by avibootz
...