Class: ColorCode::RGB

Inherits:
Object
  • Object
show all
Defined in:
lib/color_code/rgb.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code = nil, r: 0, g: 0, b: 0) ⇒ RGB

Returns a new instance of RGB.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
# File 'lib/color_code/rgb.rb', line 5

def initialize(code=nil, r: 0, g: 0, b: 0)
  r, g, b = parse_code(code) if code
  @r = r
  @g = g
  @b = b
  raise ArgumentError.new('invalid value') if @r > 255 || @g > 255 || @b > 255
end

Instance Attribute Details

#bObject

Returns the value of attribute b.



3
4
5
# File 'lib/color_code/rgb.rb', line 3

def b
  @b
end

#gObject

Returns the value of attribute g.



3
4
5
# File 'lib/color_code/rgb.rb', line 3

def g
  @g
end

#rObject

Returns the value of attribute r.



3
4
5
# File 'lib/color_code/rgb.rb', line 3

def r
  @r
end

Instance Method Details

#distance(rgb) ⇒ Object



34
35
36
# File 'lib/color_code/rgb.rb', line 34

def distance(rgb)
  Math.sqrt((@r - rgb.r)**2 + (@g - rgb.g)**2 + (@b - rgb.b)**2)
end

#to_aObject



18
19
20
# File 'lib/color_code/rgb.rb', line 18

def to_a
  [@r, @g, @b]
end

#to_hashObject



22
23
24
# File 'lib/color_code/rgb.rb', line 22

def to_hash
  { r: @r, g: @g, b: @b }
end

#to_hslObject



26
27
28
# File 'lib/color_code/rgb.rb', line 26

def to_hsl
  ColorCode::HSL.new(h: h, s:hsl_s, l:l)
end

#to_hsvObject



30
31
32
# File 'lib/color_code/rgb.rb', line 30

def to_hsv
  ColorCode::HSV.new(h: h, s:hsv_s, v:v)
end

#to_sObject



13
14
15
16
# File 'lib/color_code/rgb.rb', line 13

def to_s
  rgb = to_a.map { |hue| '%02x' % hue }.join
  "##{rgb}"
end