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 RGB format with Ruby

1 Answer

0 votes
# Generate a random color in RGB format: rgb(R, G, B)
# This program demonstrates how numbers and bits are used
# to produce valid 8‑bit channel values.

# Create a random 8‑bit integer (0–255).
# rand(256) returns a number in [0, 256),
# giving exactly one byte of color data.
def random_channel
  # 8 bits → values from 0 to 255
  rand(256)
end

# Produce a random RGB color by combining the channels.
def generate_random_rgb
  r = random_channel   # Red channel (8 bits)
  g = random_channel   # Green channel (8 bits)
  b = random_channel   # Blue channel (8 bits)

  # Construct the CSS-style RGB string
  rgb = "rgb(#{r}, #{g}, #{b})"

  { r: r, g: g, b: b, rgb: rgb }
end

# Run the program
result = generate_random_rgb

puts "Red (8 bits): #{result[:r]}"
puts "Green (8 bits): #{result[:g]}"
puts "Blue (8 bits): #{result[:b]}"
puts "RGB color: #{result[:rgb]}"


=begin
run:

Red (8 bits): 231
Green (8 bits): 4
Blue (8 bits): 204
RGB color: rgb(231, 4, 204)

=end

 



answered 1 day ago by avibootz
...