Ruby Staircase Puzzle

The HackerRank puzzle I did this morning was a lot of fun, so I thought I’d share!

The puzzle was to create a “staircase” output where you’re given a number (let’s say 6), and should produce an output like this:

     #
    ##
   ###
  ####
 #####
######

The output should have an increasing number of right-aligned hashes #, up to the number given (so 6 lines in this case).

Here’s the final solution I came up with in Ruby:

def staircase(n)
  arr = (0...n).to_a.reverse.map do |i|
    arr = Array.new(n, "#")
    arr.fill(" ", 0...i)
    arr.join
  end
  puts arr.join("\n")
end

My basic idea was to create an array of chars for each line of the output, so the third line would be:

[" "," "," ","#","#","#"]

This led to discover the fill method, which sets a range of array elements to a new value (fancy 🥂!).

Since I wanted to each line’s array to have an increasing number of hashes at the end of the array, I decided to map over an array of decreasing numbers based on the input:

(0...6).to_a.reverse   #=> [5,4,3,2,1]

This allowed me to create a fully-filled array in each loop, and zero-out the front of array based on the current number:

arr = Array.new(6, "#")   #=> ["#","#","#","#","#","#"]
arr.fill(" ", 0...3)      #=> [" "," "," ","#","#","#"]

All that’s left then is to join each sub-array, and then join("\n") final array to get the staircase!

I’ve been doing some of these smaller puzzles each day before any of my “big” work, and I’ve really enjoyed it. It’s a great way to have fun and try weird/new ideas.