 # adding a array up ?

hello I have a question about the elements of a array up

say i have array x=[1,2,3,4,5]

and i want to add all the numbers up so the output would be 15

what would be the easiest way of doing this ?

thanks for the help

Gabriel

hello I have a question about the elements of a array up

say i have array x=[1,2,3,4,5]

and i want to add all the numbers up so the output would be 15

what would be the easiest way of doing this ?

x.sum

Fred

well that didnt seem to work i did find a method that does work

no im just trying to figure out how only add up the first 9 number
form the array
and then the last 9 numbers and be able to display them seperatly

You will most likely need to iterate through the array. I would
duckpunch/monkeypatch Array if it's used often (and create a sum
method, which does not exist in the standard library).

x=[1,2,3,4,5]
x.sum

# In Array >>
def sum
a=0
self.each {|i| a += i if i.is_a? Fixnum }
a
end

Not very elegant, but a good start!

Andrew.

Thanks

(5..10).inject {|sum, n| sum + n } #=> 45

so

[1, 2, 3].inject{|sum, n| sum + n } #=> 6

regarding the first and last 9 elements -

a=%w(1 2 3 4 5 6 7 8 9 10 11 12)
a[0...9].inject{|sum, n| sum + n } #=> sum of your first 9
a[a.length-9...-1].inject{|sum, n| sum + n } #=> sum of your last 9

a.first(9).inject{|sum, n| sum + n } #=> sum of your first 9
a.last(9).inject{|sum, n| sum + n } #=> sum of your last 9

Much more obvious (and works fine for a.length < 9, too).

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com

That's just beautiful.

regarding the first and last 9 elements -

a=%w(1 2 3 4 5 6 7 8 9 10 11 12)
a[0...9].inject{|sum, n| sum + n } #=> sum of your first 9
a[a.length-9...-1].inject{|sum, n| sum + n } #=> sum of your last 9

a.first(9).inject{|sum, n| sum + n } #=> sum of your first 9
a.last(9).inject{|sum, n| sum + n } #=> sum of your last 9

or a.first(9).sum etc...

Fred

regarding the first and last 9 elements -

a=%w(1 2 3 4 5 6 7 8 9 10 11 12)
a[0...9].inject{|sum, n| sum + n } #=> sum of your first 9
a[a.length-9...-1].inject{|sum, n| sum + n } #=> sum of your last 9

a.first(9).inject{|sum, n| sum + n } #=> sum of your first 9
a.last(9).inject{|sum, n| sum + n } #=> sum of your last 9

or a.first(9).sum etc...

Fred

But with plain vanilla Ruby 1.8.6:

[1,2,3].sum

NoMethodError: undefined method `sum' for [1, 2, 3]:Array
from (irb):1

whereas #first and #last exist.

-Rob

Ya, Rails adds the sum method to Enumerable, so it should work within
a rails app.