Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Forked from brenfrow/triangle.rb
Created June 29, 2012 17:59
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 myronmarston/3019633 to your computer and use it in GitHub Desktop.
Save myronmarston/3019633 to your computer and use it in GitHub Desktop.
triangle
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