Jump to content

Pascal's triangle: Difference between revisions

Adding the Ruby implementation.
(Adding the Ruby implementation.)
Line 213:
}
}</java>
 
=={{header|Ruby}}==
<ruby>
def pascal(n)
 
# set up a new array of arrays with the first value
p = [[1]]
# for n number of times,
n.times do |i|
 
# inject a new array starting with [1]
p << p[i].inject([1]) do |result, elem|
# if we've reached the end, tack on a 1.
# else, tack on current elem + previous elem
if p[i].length == result.length
result << 1
else
result << elem + p[i][result.length]
end
end
end
# and return the triangle.
p
end
</ruby>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.