请原谅这个问题的简单性。我正在学习TDD并有以下声明。

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

我对这个问题做了一个非常基本的解决方案,并希望从更有经验的程序员那里获得关于其他解决方案的反馈。
我的代码:
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

最佳答案

通过对边进行排序,可以简化条件检查

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

或者更简单的方法是使用.uniq
sides = [a, b, c].uniq
type = case sides.length
        when 1 then :equilateral
        when 2 then :isosceles
        when 3 then :scalene
       end

关于ruby - 用Ruby测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13751773/

10-11 18:35