Pascal's Triangle in Ruby
Jun 28 2006
My friend Brent posted a solution to the most recent ruby quiz today. When I saw it, I tried to put it out of my mind. But curiosity, coupled with the fact that I seldom get to write any ruby these days, finally proved too much. As an act of rebellion against the overwhelming curiosity, I committed to do it in the most hideously unreadable form imaginable, a single expression …
#!/usr/bin/env ruby
puts (0...ARGV.first.to_i).inject([[1]]) { |a,x|
a.unshift a.first.inject([0,[]]) { |b,y|
[y,b.last << (b.first + y)]
}.last + [1]
}.inject([]) { |c,z|
next [z[z.length/2].to_s.length*2,z.length,""] if c.empty?
[c[0],c[1], z.map { |j|
j.to_s.center(c[0])
}.join('').center(c[0]*c[1])+"\n#{c.last}"]
}.last
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1
Check out more ruby quizzes with far less hideous solutions in the ruby quiz archive.