One liner for Project Euler problem 20
I was needlessly worrying about about the capabilities of Bignum in being able to handle this factorial which has 158 digits in its result. Wasn’t an issue at all though.
Ruby certainly brings conciseness to the code. It maybe possible in a lot lesser characters in J or other functional languages, but this is good enough for me for the time being.
The problem statement is
Find the sum of the digits in the number 100!
Solution in Ruby
puts (1..100).to_a.inject{|prod, n| prod * n}.to_s.split(//).map{|d| d.to_i}.inject{|sum, n| sum + n}
Edit: even shorter with the reduce method in Ruby 1.9
(1..100).reduce(:*).to_s.split(//).map{|d| d.to_i}.reduce(:+)