[ next ] [ prev ] [ contents ] Invitation To Ruby

Iterator Example

  1: #!/usr/bin/env ruby
  2: 
  3: module Enumerable
  4:   # Reduce has been added to the Ruby 1.7 library
  5:   def reduce(init)
  6:     result = init
  7:     each { |item| result = yield(item, result) }
  8:     result
  9:   end
 10: end
 11: 
 12: puts [1,2,3,4].reduce(0) { |n, sum| n + sum }
 13: puts [1,2,3,4].reduce(1) { |n, prod| n * prod }

Output

10
24


[ next ] [ prev ] [ contents ] Copyright 2002 by Jim Weirich.
All rights reserved.