From: Rob Biedenharn Date: 2008-09-22T05:28:08+09:00 Subject: Re: iterating methods on multiple parameters On Sep 21, 2008, at 3:57 PM, Jason Lillywhite wrote: > Thanks everyone! > > Is there a reason the hsh.inject method is not included in the Ruby > documentation? Sure it is. In my Programming Ruby, 2 ed., on page 492 it say that Hash mixes in the Enumerable module and lists inject as one of the methods. Enumerable#inject itself is documented on page 456. Depending on where/how you're looking, it is! $ ri Hash#inject Nothing known about Hash#inject $ fri Hash#inject ------------------------------------------------------ Enumerable#inject enum.inject(initial) {| memo, obj | block } => obj enum.inject {| memo, obj | block } => obj ------------------------------------------------------------------------ Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn. At each step, memo is set to the value returned by the block. The first form lets you supply an initial value for memo. The second form uses the first element of the collection as a the initial value (and skips that element while iterating). # Sum some numbers (5..10).inject {|sum, n| sum + n } #=> 45 # Multiply some numbers (5..10).inject(1) {|product, n| product * n } #=> 151200 # find the longest word longest = %w{ cat sheep bear }.inject do |memo,word| memo.length > word.length ? memo : word end longest #=> "sheep" # find the length of the longest word longest = %w{ cat sheep bear }.inject(0) do |memo,word| memo >= word.length ? memo : word.length end longest #=> 5 What leads you to think that it isn't documented? -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com