Solved the classic Tower of Hanoi problem in Ruby, using recursion. Would love your feedback on this.# Excellent explanation of the solution at # http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/13/hanoi.htmlMove =   Struct.new :disk, :from, :to do    def to_s      Disk #{disk}: #{from} -> #{to}    end  enddef spare_peg(from, to)  # returns the peg that is not 'from' nor 'to'  # e.g. if from=A, to=C ... then spare=B  [*A..C].each {|e| return e unless [from, to].include? e}enddef hanoi(num, from, to)  if num == 1 # base case    return [Move.new(num, from, to)]  end  spare = spare_peg(from, to)  moves = hanoi(num - 1, from, spare) # move everything to the spare peg  moves << Move.new(num, from, to) # move the sole remaining disk to the 'to' peg  moves += hanoi(num - 1, spare, to) # move all the disks on top of the 'to' pegendSample output:puts hanoi(3, A, B).each {|move| move.to_s}Disk 1: A -> BDisk 2: A -> CDisk 1: B -> CDisk 3: A -> BDisk 1: C -> ADisk 2: C -> BDisk 1: A -> B
Tower of Hanoi solver in Ruby
algorithm;ruby;recursion
Looks good!For the spare_peg you could use detect (which can be called on a range)(A..C).detect { |peg| ![from, to].include?(peg) }or some array arithmetic:([*A..C] - [from, to]).first(I'd just use detect.)And a minor thing: I'd use parentheses for declaring the Struct.new call, just for consistency.