Search code examples
rubypascals-triangle

Pascal's Triangle in Ruby


I am writing Pascal's triangle in Ruby, but keep getting the error message:

pascalsTriangle.rb:3:in 'triangle': undefined method `each' for 4:Fixnum (NoMethodError)
from pascalsTriangle.rb:18

def triangle(n)
  for r in n:
    lst=[1]
    term=1
    k=0
    (0..r+1).step(1){ |index|
      term=term*(r-k+1)/k
      lst.append(term)
      k+=1
    }
    print lst
  end
end

triangle(4)

Solution

  • the final source code:

    def triangle(n)
        (0..n).each{|r|
                lst=[1]
                term=1
                k=1
                (0..r-1).step(1){|index|
                        term=term*(r-k+1)/k
                        lst.push term 
                        k+=1
                }
                p lst
        }
    end
    triangle(4)
    

    changes:

    1. you have syntax error on for r in n:.
    2. a logical error on k=0 that causes Division by zero.
    3. (0..r+1) is changed to (0..r-1)
    4. there is no append method for array. changed to push
    5. p is used instead of print