# \[QUIZ\] pp Pascal (#84)

**URL:** <https://www.ruby-forum.com/t/quiz-pp-pascal-84/96495>\
**Category:** Ruby\
**Created:** [June 29, 2006, 1:20am UTC](https://www.ruby-forum.com/t/quiz-pp-pascal-84/96495 "2006-06-29T01:20:53Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Devin\_Chalmers](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/50afbb/32.png) [@Devin\_Chalmers](https://www.ruby-forum.com/u/Devin_Chalmers)\
**Post date:** [June 29, 2006, 1:20am UTC](https://www.ruby-forum.com/t/quiz-pp-pascal-84/96495/1 "2006-06-29T01:20:53Z")

</div>

Hello everyone! This is my first quiz submission.

I suppose it’s a little verbose, but I feel it’s clever enough. I do  
the straightforward, plain-vanilla recursive building of the triangle  
right from the Array constructor, which is kinda cool, then extend the  
Array class to print it out. (The to\_centered\_spaced\_string method  
really only works on a fairly specific subset of 2D arrays,  
unfortunately.)

And, thanks for the quizzes! I have enjoyed the past entries greatly.

Devin Chalmers

PS - sorry for the 81-char line. I hate it too. 🙂

==== pp\_pascal.rb

#!/usr/local/bin/ruby

def pascal\_cell(row, col)  
return 1 if col == 0 or col == row  
return pascal\_cell(row - 1, col) + pascal\_cell(row - 1, col - 1)  
end

def pascal\_array(depth)  
Array.new(depth) {|i| Array.new(i + 1){|j| pascal\_cell(i, j)}}  
end

class Array  
def to\_centered\_spaced\_string  
cell\_width = self.flatten.collect{|val| val.to\_s.size}.max + 2  
row\_width = self.collect{|row| row.size}.max \* cell\_width  
rows = Array.new(self.size) do |i|  
self[i].collect{|item|item.to\_s.center(cell\_width)}.join.center(row\_width)  
end  
return rows.join("\n")  
end  
end

puts pascal\_array(ARGV[0].to\_i).to\_centered\_spaced\_string
