Created
October 9, 2013 13:41
-
-
Save davidbella/6901480 to your computer and use it in GitHub Desktop.
Ruby: Triangle classifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TriangleError < StandardError | |
end | |
class Triangle | |
def initialize(s1, s2, s3) | |
@sides = [s1, s2, s3] | |
if @sides.any? {|side| side <= 0} | |
raise TriangleError.new, "Cannot create a triangle " | |
end | |
@sides.combination(2).each do |combination| | |
last_side = @sides.clone | |
combination.each {|item| last_side.delete(item)} | |
if !last_side.empty? && combination.inject(:+) <= last_side.first | |
raise TriangleError.new, "Cannot create a triangle" | |
end | |
end | |
classify | |
end | |
def classify | |
if @sides.uniq.count == 1 | |
@kind = :equilateral | |
elsif @sides.uniq.count == 2 | |
@kind = :isosceles | |
else | |
@kind = :scalene | |
end | |
end | |
def kind | |
@kind | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment