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 random color in HEX format with Ruby

1 Answer

0 votes
# Generate a random color in HEX format (#RRGGBB)
# This program demonstrates how numbers and bits are used
# to produce a valid 24‑bit color value.

# Create a 24‑bit random integer (0x000000–0xFFFFFF).
# rand(0x1000000) returns a number in [0, 0x1000000),
# giving exactly 24 bits of color data.
def random_color_int
  # 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
  rand(0x1000000)
end

# Convert a 24‑bit integer into a hex color string.
# "%06X" ensures exactly 6 uppercase hex digits.
def int_to_hex_color(value)
  "##{format('%06X', value)}"
end

# Produce a random hex color by combining the two functions.
def generate_random_hex_color
  value = random_color_int      # 24‑bit random number
  hex   = int_to_hex_color(value) # Convert to #RRGGBB
  { value: value, hex: hex }
end

# Run the program
result = generate_random_hex_color

puts "Random 24‑bit value: #{result[:value]}"
puts "Hex color: #{result[:hex]}"


=begin
run:

Random 24‑bit value: 16747257
Hex color: #FF8AF9

=end

 



answered 1 day ago by avibootz
...