ruby 练习:计算数组totalWrite一个方法总计,它将一个数字数组作为输入并返回它们的总和(总和)。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 练习:计算数组totalWrite一个方法总计,它将一个数字数组作为输入并返回它们的总和(总和)。相关的知识,希望对你有一定的参考价值。

# PSEUDOCODE
# INPUT: an array of numbers
# OUPUT: sum of all numbers in array
# STEPS: start with a total of zero 
# 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
# My approach has typically been to start with pseudocode.  I
# 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

以上是关于ruby 练习:计算数组totalWrite一个方法总计,它将一个数字数组作为输入并返回它们的总和(总和)。的主要内容,如果未能解决你的问题,请参考以下文章

Ruby - 解密使用:[重复]

ruby 练习:计算一系列成绩的字母等级创建一个接受一系列考试成绩的方法get_grade。每个得分都在

Ruby 批处理数组用于对讲

如何从文件中将文本读入ruby中的数组

练习数值计算。找出一个整数数组中子数组之和的最大值。

计算字符在Ruby中的字符串数组中出现的次数