Tower of Hanoi solver in Ruby 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.html

Move = 
  Struct.new :disk, :from, :to do
    def to_s
      "Disk #{disk}: #{from} -&gt; #{to}"
    end
  end

def 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}
end

def 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 &lt;&lt; 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' peg
end


Sample output:


  puts hanoi(3, "A", "B").each {|move| move.to_s}


Disk 1: A -&gt; B
Disk 2: A -&gt; C
Disk 1: B -&gt; C
Disk 3: A -&gt; B
Disk 1: C -&gt; A
Disk 2: C -&gt; B
Disk 1: A -&gt; B
Obviously this is one of those things which is opinionated but:

1) It might be simpler to use num.zero? as your base case 

2) I would pass the spare tower as a parameter rather than calculating it all the time.

Something like:

def hanoi(num, from, to, spare)
  return [] if num.zero?                   # base case

  moves =  hanoi(num - 1, from, spare, to) # move everything to the spare peg
  moves &lt;&lt; Move.new(num, from, to)         # move the sole remaining disk to the 'to' peg
  moves += hanoi(num - 1, spare, to, from) # move all the disks on top of the 'to' peg
end