Module: ColorMath

Extended by:
ColorMath
Included in:
ColorMath
Defined in:
lib/colormath.rb,
lib/colormath/blend.rb,
lib/colormath/color.rb,
lib/colormath/version.rb,
lib/colormath/color/hsl.rb,
lib/colormath/color/rgb.rb

Defined Under Namespace

Modules: Blend, Color, VERSION Classes: HSL, RGB

Constant Summary collapse

ParsingError =
Class.new(RuntimeError)

Instance Method Summary collapse

Instance Method Details

#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