09f29a1cb5a7c670532ba4bb1b224758

This code performs triangle analyzes. I want it to look more elegant...

# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
#   :equilateral  if all sides are equal
#   :isosceles    if exactly 2 sides are equal
#   :scalene      if no sides are equal
#
def triangle(a, b, c)
  raise TriangleError, "Wrong length" if [a,b,c].any? { |e| e <= 0 }
  [a,b,c].zip([b,c,a], [c,a,b]).each do |arr|
    raise TriangleError, "Too small" if arr[0] >= arr[1] + arr[2]
  end
  uniqe_elements = [a,b,c].uniq.length;
  return :equilateral if uniqe_elements == 1
  return :isosceles if uniqe_elements == 2
  :scalene
end

Refactorings

No refactoring yet !

D85d44a0eca045f40e5a31449277c26c

Ben Marini

October 18, 2010, October 18, 2010 15:36, permalink

1 rating. Login to rate!
class TriangleError < StandardError; end

def triangle(a, b, c)
  if [a,b,c].any? { |e| e <= 0 }
    raise TriangleError, "Wrong length"
  end

  if [ [a,b+c], [b,a+c], [c,a+b] ].any? { |(side, sum)| side >= sum }
    raise TriangleError, "Too small"
  end

  case [a,b,c].uniq.length
  when 1 then :equilateral
  when 2 then :isosceles
  else;       :scalene
  end
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

October 18, 2010, October 18, 2010 19:06, permalink

No rating. Login to rate!

Doesn't the "Too small" check make finding scalene triangles impossible?

class TriangleError < StandardError; end
class WrongLengthError < TriangleError; end

def triangle(*sides)
  raise(ArgumentError, "wrong number of arguments (#{sides.size} for 3)") if sides.size != 3
  raise(WrongLengthError, "wrong length (#{sides.join(', ')}, must be all greater than zero)") if sides.any? { |side| side <= 0 }
  
  return :equilateral if sides.uniq.size == 1
  return :isosceles if sides.uniq.size == 2
  return :scalene
end
2ba827bff28c7ee3a629782c8d14aa3b

livelybrowsers

October 19, 2010, October 19, 2010 16:37, permalink

No rating. Login to rate!

Thanks for good stuff

Your refactoring





Format Copy from initial code

or Cancel