-
-
Save myronmarston/3019633 to your computer and use it in GitHub Desktop.
triangle
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
TriangleError = Class.new(ArgumentError) | |
Triangle = Struct.new(:x, :y, :z) do | |
def initialize(*args) | |
super | |
validate | |
end | |
def type | |
TYPES.fetch(uniq_side_lengths) | |
end | |
private | |
TYPES = { 1 => :equilateral, 2 => :isosceles, 3 => :scalene } | |
def validate | |
raise TriangleError if has_disallowed_side_length? || side_too_long? | |
end | |
def has_disallowed_side_length? | |
[x, y, z].any? { |v| v <= 0 } | |
end | |
def side_too_long? | |
x + y <= z || y + z <= x || z + x <= y | |
end | |
def uniq_side_lengths | |
[x, y, z].uniq | |
end | |
end | |
def triangle(x, y, z) | |
Triangle.new(x, y, z).type | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment