Skip to content

Instantly share code, notes, and snippets.

@ernest-ns
Created June 15, 2016 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ernest-ns/3fcf4c6fa6446b6bd67ebaf9c687d451 to your computer and use it in GitHub Desktop.
Save ernest-ns/3fcf4c6fa6446b6bd67ebaf9c687d451 to your computer and use it in GitHub Desktop.
A color class to calculate the distance between 2 colors.
class MyColor
attr_accessor :red, :blue, :green, :alpha
def initialize(args)
@red = args[:red]
@blue = args[:blue]
@green = args[:green]
@alpha = args[:alpha] || 1
end
def distance(color)
red_diff = self.red - color.red
blue_diff = self.blue - color.blue
green_diff = self.green - color.green
alpha_product = self.alpha * color.alpha
(100) * Math.sqrt(((red_diff ** 2) + (blue_diff ** 2) + (green_diff ** 2)) * alpha_product/3 + (self.alpha - color.alpha) ** 2)
end
def distance_in_percentage(color)
(distance(color) * 100) / 25000
end
end
c1 = MyColor.new({red: 233, green: 233, blue: 233})
c2 = MyColor.new({red: 102, green: 102, blue: 102})
c3 = MyColor.new({red: 212, green: 212, blue: 204})
c4 = MyColor.new({red: 232, green: 232, blue: 232})
c5 = MyColor.new({red: 0, green: 0, blue: 0})
c4.distance_in_percentage(c2)
c1.distance_in_percentage(c4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment