Method: ColorMath#hex_color

Defined in:
lib/colormath.rb

#hex_color(s) ⇒ Object

Instantiate an RGB colour from a 3- or 6-digit hexadecimal representation. “#abc”, “#abcdef”, “abc”, and “abcdef” are all valid.

Invalid representations will raise a ParsingError.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/colormath.rb', line 9

def hex_color(s)
  if m = s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i)
    RGB.new( m[1].to_i(16) / 255.0,
             m[2].to_i(16) / 255.0,
             m[3].to_i(16) / 255.0 )
  elsif m = s.match(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i)
    RGB.new( (m[1] + m[1]).to_i(16) / 255.0,
             (m[2] + m[2]).to_i(16) / 255.0,
             (m[3] + m[3]).to_i(16) / 255.0 )
  else
    raise ParsingError, "invalid hex sequence '#{s}'"
  end
end