loading...

re: Daily Challenge #158 - RGB To Hex Conversion VIEW POST

FULL DISCUSSION
 

Ruby solution

def valid_num(v)
  [[v, 255].min, 0].max
end

def rgb(*args)
  args[0..2].reduce('') { |str, v|
    str << valid_num(v).to_s(16).rjust(2, '0')
  }
end
 

Note that you can use a format string to do most of the work for you:

# before
valid_num(v).to_s(16).rjust(2, '0')

# after
"%02X" % valid_num(n)

You can also use "%0x" if you want the hex digits to be lowercase.

 

Thanks for the tip! I've mostly used string formating for dealing with point numbers in decimals. Need to explore more use cases because the syntax is indeed preferable.

Code of Conduct Report abuse