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 ?
thanks for the help
Gabriel
On 18 Jun 2008, at 01:28, GabrielG1976 wrote:
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
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
From http://www.ruby-doc.org/core-1.8.4/classes/Enumerable.html#M002101
(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
On Jun 18, 2008, at 9:56 AM, ahab wrote:
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
On 18 Jun 2008, at 15:07, Rob B. wrote:
a.last(9).inject{|sum, n| sum + n } #=> sum of your last 9
or a.first(9).sum etc…
Fred
On Jun 18, 2008, at 12:59 PM, Frederick C. wrote:
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 9or a.first(9).sum etc…
Fred
But with plain vanilla Ruby 1.8.6:
irb> [1,2,3].sum
NoMethodError: undefined method `sum’ for [1, 2, 3]:Array
from (irb):1
from :0
whereas #first and #last exist.
-Rob
Ya, Rails adds the sum method to Enumerable, so it should work within
a rails app.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs