Luis F. Vidal Luis F. Vidal - 1 year ago 217
Ruby Question

Pascal Triangle in Ruby

I'm trying to write a method to generate Pascal's triangles as a 2D array. For example:

pascal(3) # => [[1],[1,1],[1,2,1]]

Here is my code:

def pascal n
pascal = []
row = [1]
(1...n).each do |i|
#first iteration set pascal equal to [[1]] and row to [1,1]
pascal << row
#sets new value for row for next iteration
row = [1,1]
#row generator sets new value for row
row = ([0] + row).zip(row + [0]).collect { |a, b| a + b }
#push row's new value into pascal array
pascal << row

I know the row generator works fine, I've tested myself with irb. The output is
, as if it didn't run.

Any idea what's wrong with my code? Please, be gentle, as you can see I'm a newbie. Thanks in advanced :)

Answer Source

Return value of ruby method is the last thing evaluated. In your case, it's each. each returns a thing it iterated (the range). You should explicitly return pascal array from your method as this seems to be the result you need. Add this line to the end of your method.

      pascal << row
    end # end if
  end # end each

  pascal # < this line

end # end method

This will make pascal the last thing evaluated and, therefore, return value of the method.

JFYI, it seems that your code has broken logic. If we do the abovementioned correction, we get this (which does not match your expectation).

pascal(3) # => [[1, 1], [1, 2, 1]]

I leave it up to you to debug this. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download