Am 25.06.2013 10:32, schrieb Tamara Temple:
> Let's drop back a second and just look at the algorithm one can use to
> find the sum of number in an array. No ruby, just pseudo-code.
>
> Given an array of numeric elements,
> When I initialize a sum variable to zero,
> And I loop through the array with an index,
> And I add the value of the array element at the current index to the sum
> variable,
> Then I will have the sum of the elements in the array.

...
> But let's look at this in a method:
>
> === sum.rb
> def sum(a) # Given an array of numeric elements,
>    sum = 0 # When I initialize a sum variable to zero,
>    a.each_index do |i| # And I loop through array with an index,
>      sum += a[i] # And I add the value of the array element
>                  # at the current index to the sum
>                  # variable,
>    end
>    sum # Then I will have the sum of the elements in the array.
> end
> ===
>
> 2.0.0p195 :010 > def sum(a) ; sum=0;a.each_index{|i| sum+=a[i]}; sum; end
>   => nil
> 2.0.0p195 :011 > sum x
>   => 55

There's no need to use the each_index here at all!
Simply loop through each array element (with `each`).

> There's at least a dozen ways to write this; this is but one. Comparing
> the method sum to inject, I much prefer inject.

Considering the knowledge level of the OP, I strongly agree here
with Mike Stok: "There are other ways to do it, but you should
master the basics so you can understand the more advanced methods."

Of course, in "real life" anyone would use inject.

Regards,
Marcus


-- 
<https://github.com/stomar/>