Sum method through while loops or iteration

I am trying to create a sum method for an empty array, that will return
“0” if there is nothing in it and the sum of the values if there are
values called through it. I have seen other ways on the internet, but I
am relatively new to this, and am under the impression that this can be
done with while loops or .each iteration. Below are various things I
tried, some were actual thoughts some were out of sheer frustration.
Thanks for your help!
1.
def sum (array)

array = []

while array >0
array.each { |a| sum+=a }

end

def sum
x= []
x.each{|element| element +element }

end

def sum(array)

while array.length > 0
puts “#{array[x+y+z]}”
else
puts “0”

On 2013-06-24, at 7:33 PM, “Eric D.” [email protected] wrote:

array = []

while array >0
array.each { |a| sum+=a }

end

It can be done with loops, and you need to think through what you are
trying to do.

Maybe:

  1. Initialize the sum to 0
  2. For each value in the array, add that value to the sum

which translates into ruby something like this:

array = [2, 4, 6, 9, 11]

sum = 0
array.each { |val| sum += val }

puts “sum is #{sum}”

would be a place to start, and then you can package it up into a method,
once you understand what each line does.

There are other ways to do it, but you should master the basics so you
can understand the more advanced methods.

Hope this helps,

Mike

def sum(array)

while array.length > 0
puts “#{array[x+y+z]}”
else
puts “0”


Posted via http://www.ruby-forum.com/.

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

“Jesús Gabriel y Galán” [email protected] wrote in post
#1113505:

2.- More functional styles:

2.0.0p195 :029 > a.inject(0) {|total, x| total + x}
=> 10
2.0.0p195 :030 > a.inject(:+)
=> 10

there is a difference:

[].inject(0) {|total, x| total + x}
=> 0
[].inject(:+)
=> nil

so i think this would be the best:

[].inject(0,:+)
=> 0

There already is a standard method for this:

irb(main):001:0> a = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):002:0> a.reduce(0) { |a,b| a+b }
=> 10
irb(main):003:0> a = []
=> []
irb(main):004:0> a.reduce(0) { |a,b| a+b }
=> 0

(Btw, “reduce” is the same as “inject”, but I prefer the former as this
describes the behaviour, and doesn’t allude to an infix syntax.)

On Tue, Jun 25, 2013 at 1:33 AM, Eric D. [email protected] wrote:

array = []

while array >0
array.each { |a| sum+=a }

end

You cannot compare an array to an integer. array > 0 doesn’t make
sense. You are probably getting this error when you run this:

2.0.0p195 :001 > a = []
=> []
2.0.0p195 :002 > a > 0
NoMethodError: undefined method `>’ for []:Array
from (irb):2

The next line is actually pretty near a solution. The only problem is
that sum in that block is just a local variable to the block, so when
you are outside of the block, you don’t see it anymore. A way to fix
it is to declare the variable outside initialized to 0:

sum = 0
array.each {|a| sum += a}

The other thing you need to know is that a Ruby method will return
whatever the result of the last line is. In this case, your last line
is calling the each method, which returns the original array. You have
to return the sum, like so:

2.0.0p195 :003 > def sum
2.0.0p195 :004?> a = [1,2,3]
2.0.0p195 :005?> sum = 0
2.0.0p195 :006?> a.each {|x| sum += x}
2.0.0p195 :007?> sum
2.0.0p195 :008?> end
=> nil
2.0.0p195 :009 > sum
=> 6

def sum
x= []
x.each{|element| element +element }

end

Here, the problem is that you are summing twice each element of the
array (which is not what you want), but also, you are not doing
anything with the result of that sum. What you do inside the block of
“each” is not seen from the outside of the block, unless you assign it
to a variable that can be seen outside.

def sum(array)

while array.length > 0
puts “#{array[x+y+z]}”
else
puts “0”

In this case, array.length will either always be greater than 0 or
not, since you are not modifying the array within the while loop. You
could remove the elements to decrease the length, but this is not a
very good solution for many reasons.

Here are a couple more ways to do it:

1.- More procedural style:

2.0.0p195 :012 > sum = 0
=> 0
2.0.0p195 :017 > a = [1,2,3,4]
=> [1, 2, 3, 4]
2.0.0p195 :018 > for i in 0…a.length
2.0.0p195 :019?> sum += a[i]
2.0.0p195 :020?> end
=> 0…4
2.0.0p195 :021 > sum
=> 10

2.- More functional styles:

2.0.0p195 :029 > a.inject(0) {|total, x| total + x}
=> 10
2.0.0p195 :030 > a.inject(:+)
=> 10

I think if you understand the first example above, using “each”, you’ll
be good:

sum = 0
array.each {|a| sum += a}
puts sum

Hope this helps,

Jesus.

On Tue, Jun 25, 2013 at 9:44 AM, Hans M. [email protected]
wrote:

there is a difference:

[].inject(0) {|total, x| total + x}
=> 0
[].inject(:+)
=> nil

Good catch !

Jesus.

Eric D. [email protected] wrote:

I am trying to create a sum method for an empty array, that will return
“0” if there is nothing in it and the sum of the values if there are
values called through it. I have seen other ways on the internet, but I
am relatively new to this, and am under the impression that this can be
done with while loops or .each iteration. Below are various things I
tried, some were actual thoughts some were out of sheer frustration.

I applaud all efforts to learn how things work. That said, there is a
method which does this already: inject/reduce (they are synonyms).

But let’s look at what you’re doing.

Thanks for your help!
1.
def sum (array)

The method accepts an array passed in local variable array.

array = []

You destroy any information you’ve passed in array by resetting it
here.

while array >0

This construction makes little sense, as an Array (array is an
instance of the Array class) cannot be compared to a Fixnum (which is
what 0 is.)

But then:

array.each { |a| sum+=a }

You use another loop to run through array. This is probably what you
mean entirely and there is no need for an outer while loop.

However, the local variable sum is declared implicitly inside the
block {|a| sum+=a}. There are two problems here:

  1. sum is initially nil, and nil does not accept += (or +)
  2. sum will not be available outside the block

end

def sum
x= []

This time, you aren’t overwriting any method input, but you also
hardwire the x array to an empty array. Not a very useful method.

x.each{|element| element +element }

More problems here. You’ve omitted the egregious while loop, which is
good. But your block is not doing anything in particular. The current
element in x is added to itself, but isn’t stored anywhere.

Trying this out in irb:

2.0.0p195 :001 > x = (1…10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2.0.0p195 :002 > x.each{|e| e+e}
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2.0.0p195 :003 >

To see what’s happening inside the block, let’s add tap:

2.0.0p195 :003 > x.each{|e| (e+e).tap{|t| puts “tapped e+e: #{t}”} }
tapped e+e: 2
tapped e+e: 4
tapped e+e: 6
tapped e+e: 8
tapped e+e: 10
tapped e+e: 12
tapped e+e: 14
tapped e+e: 16
tapped e+e: 18
tapped e+e: 20
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Probably not what you wanted.

end

def sum(array)

while array.length > 0

This may seem like it should work, but you are not actually changing the
length of array so it should go on forever.

puts "#{array[x+y+z]}"

This is insteresting, but where do you define the variables x, y,
and z? This should have elicited an error message straight away.

else
puts “0”

There was no end in this block.

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.

Someone’s already given the inject/reduce version:

(using x from before)

2.0.0p195 :007 > x.inject(:+)
=> 55

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 at least a dozen ways to write this; this is but one. Comparing
the method sum to inject, I much prefer inject.

Am 25.06.2013 10:32, schrieb Tamara T.:

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.

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 S.: “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