メソッドfoldの定義が冗長だったので、>>42を訂正する

def fold(init, xs, &fn)
  if xs.empty?
    init
  else
    result = fn.call(init, xs[0])
    for x in xs[1..(xs.length - 1)]
      result = fn.call(result, x, &fn)
    end
    result
  end
end

def sum(ary); fold(0, ary) { |s, x| s + x }; end
def product(ary); fold(1, ary) { |p, x| p * x }; end
def reverse(ary); fold([], ary) { |xs, x| xs.unshift(x) }; end
def length(ary); fold(0, ary) { |n, _| n + 1 }; end