I'm trying to use Ruby's inject to sum an array representing a finite continued fraction, where
[a, b, c, d, e, ... , x] = a + 1/(b + 1/(c + 1/(d + 1/(e + ... 1/x)...)))
I can't figure out how to get the proper nested evaluation to return the correct value using inject.
Instead, what I've written just returns the flat sum of the terms rather than a nested sum. For example,
total = [0, 2, 1, 12, 8].inject do |sum,x|
sum = sum + Rational(1,x)
end
puts total
#=> 41/24
That is,
0 + 1/2 + 1/1 + 1/12 + 1/8 #=> 41/24
instead of
0 + 1/(2 + 1/(1 + 1/(12+1/8))) #=> 105/307
, which is the correct value.
Is it possible to compute this type of sum using the inject method?
If not, how can I compute it correctly?