carolineartz
1/8/2014 - 2:35 AM

## Exercise: Calculating the array total Write a method total which takes an Array of numbers as its input and returns their total (sum).

Exercise: Calculating the array total Write a method total which takes an Array of numbers as its input and returns their total (sum).

``````# PSEUDOCODE
# INPUT: an array of numbers
# OUPUT: sum of all numbers in array
# iterate over each element in the array
# for each element, add its value to the total
# return the total after there are no more elements

# INITIAL CODE:
def total(array)
total = 0
array.each do | x |
total += x
end
total
end

# REFACTORED CODE:
def total(array)
array.reduce(:+)
end

# REVIEW/REFLECT
# solved this challenge to my initial code pretty easily simply by translating
# my pseudocode from ~english to code using the most basic of methods. At
# times, I think if I know one way to acheieve the goal in Java and how that
# could map to Ruby. Here, instead of using a for loop I went for ruby's #each
# (knowing Ruby's for loop is less preferable).

# Though there isn't much repetition but a good candidate for the refactoring
# practice:  Replace Loop with Collection Closure Method (because of my
# original #each).  I remember that #inject and #reduce do something of this
# sort and learning more about them was very helpful. I prefer #reduce simply
# because its easier for me to conceptualize given the method name vs.
# #inject. Using ruby docs via Alfred -> Dash workflow, it was easy to look
# them up, but I still find myself working through the shorthand and/or
# notation e.g., `:+` ...the use of the symbol passes the #+ method to the
# beginning of the array and accumulates across iterations  #e.g.,
# [1,2,3].reduce(:+) => 1.+2.+3 => 3.+3 => 6. I used stackoverflow  and some
# good blog posts on Enumerables and collections to look into the concepts.
# Hopefully I can solidify this by using these and other enumerables

``````