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
#