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
  types[number_of_lengths]

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

2 comments:

  1. Comes back :isosceles, as is correct. Transcript from irb:

    1.9.3p194 :001 > a = b = 3
    => 3
    1.9.3p194 :002 > c = 17
    => 17
    1.9.3p194 :003 > [:equilateral, :isosceles, :scalene][[a,b,c].uniq.length - 1]
    => :isosceles

    And furthermore:

    1.9.3p194 :004 > c = 3
    => 3
    1.9.3p194 :005 > [:equilateral, :isosceles, :scalene][[a,b,c].uniq.length - 1]
    => :equilateral

    And lastly:

    1.9.3p194 :006 > a = 1
    => 1
    1.9.3p194 :007 > b = 2
    => 2
    1.9.3p194 :008 > [:equilateral, :isosceles, :scalene][[a,b,c].uniq.length - 1]
    => :scalene

    ReplyDelete

Note: Only a member of this blog may post a comment.