Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing with Ruby

Tags:

ruby

testing

Forgive the simplicity of this problem. I'm learning about TDD and have the following statements.

def test_equilateral_triangles_have_equal_sides
   assert_equal :equilateral, triangle(2, 2, 2)
   assert_equal :equilateral, triangle(10, 10, 10)
end

def test_isosceles_triangles_have_exactly_two_sides_equal
  assert_equal :isosceles, triangle(3, 4, 4)
  assert_equal :isosceles, triangle(4, 3, 4)
  assert_equal :isosceles, triangle(4, 4, 3)
  assert_equal :isosceles, triangle(10, 10, 2)
end

def test_scalene_triangles_have_no_equal_sides
  assert_equal :scalene, triangle(3, 4, 5)
  assert_equal :scalene, triangle(10, 11, 12)
  assert_equal :scalene, triangle(5, 4, 2)
end

I made a really basic solution to this problem and wanted to get feedback from more experienced programmers about alternative solutions.

My code:

def triangle(a, b, c)
  if (a == b) && (a == c) && (b == c)
    :equilateral
  elsif (a == b) && ((a || b) != c)
    :isosceles
  elsif (a == c) && ((a || c) != b)
    :isosceles
  elsif (b == c) && ((b || c) != a)
    :isosceles
  else
    :scalene
end
like image 632
E L Avatar asked Jan 22 '26 11:01

E L


2 Answers

You can make the condition checks easier by sorting the sides

sides = [a, b, c].sort
return :equilateral if sides[0] == sides[2]
return :isosceles if sides[0] == sides[1] || sides[1] == sides[2]
return :scalene

Or an even easier way would be to count the number of unique sides using .uniq

sides = [a, b, c].uniq
type = case sides.length
        when 1 then :equilateral 
        when 2 then :isosceles 
        when 3 then :scalene
       end
like image 109
rohit89 Avatar answered Jan 25 '26 03:01

rohit89


Two comments. First, generally you want tests to confirm positive case, as well as to check for failures (assert_not_equal).

I think you could tighten up your triangle method a little.

Consider: if a == b and b == c then it is true that a == c

Consider: if a == b or b == c or a == c then a triangle is isosceles

Consider: the first condition met will prevent others from executing, and also rules out other cases.

like image 22
Tom Harrison Avatar answered Jan 25 '26 03:01

Tom Harrison