Friday, September 21, 2012

Ruby microhack: kinds of triangles

   Someone recently posted on the RubyOnRails-talk mailing list, about a little exercise he was doing as a beginning Rubyist.  The task was to construct a method that would return the type of a triangle (equilateral, isosceles, or scalene), given the three lengths.  He had the logic down fine, but needed some help with the Ruby syntax, properly ending a series of if-statements.

   A quite different way to solve it, popped into my twisted little mind:

  [:equilateral, :isosceles, :scalene][[a,b,c].uniq.length - 1]

   As I wrote to him, "Do NOT put something that "clever" in anything actually important, as the lack of clarity isn't worth the conciseness.  But it makes a neat
little mind-exercise.  ;-)"

   Alternately, to split it up for a bit better readability:

  types = [:equilateral, :isosceles, :scalene]
  number_of_lengths = [a, b, c].uniq.length - 1

   Just thought y'all might find it amusing....