使用数组方法

Working on an array method

在我的作业中,我必须为整数 class 创建一个 digit_sum 方法。结果:

class Integer
    def digit_sum
        to_s.split("").inject(0) { |sum, n| sum + n.to_i }
    end
end

现在我必须为数组创建类似的东西:

[1, 2, 3, "words"].sum #=> 6
[12, 13, 14].sum_up_digit_sums #=> 12

但我不知道如何使用数组 Class。一个简单的开始应该是这样的。

class Array
   def sum
       #Code
   end
end

数组有变量,但我不知道如何将这些变量包含到我的代码中。我希望有人能解释我应该如何处理它。

实施sum_up_digit_sums

class Array
  def sum_up_digit_sums
    join.chars.map(&:to_i).reduce(:+)
  end
end

puts [12, 13, 14].sum_up_digit_sums # => 12

您的sum要求也很满意

[12, 13, 14] 的解释:

  1. .join 将从给定的数组创建一个字符串:[12, 13, 14] => "121314"
  2. .chars 将从该字符串创建一个字符数组 "121314" => ["1", "2", "1", "3", "1", "4"]
  3. .map(&:to_i) 将在每个字符上调用 to_i ["1", "2", "1", "3", "1", "4"] => [1, 2, 1, 3, 1, 4](此时,如果您有任何单词字符,它们将变为零)
  4. 然后用.reduce(:+)简单地求和(reduceinject的别名)

让我们从第二个开始,Array#sum 方法。这是一个普遍需要的方法,也是一道实用的作业题。

首先,查看您现有的 Integer#digit_sum 实现:

# Here you're taking a number, turning it into a string, and splitting it
# on an empty string, resulting in an array of characters (same effect as 
# `String#chars`)
to_s.split("").

# The result of this?  An array, to which you're then sending `inject` to 
# calculate the sum.  As you see you've already written a rudimentary 
# `Array#sum` (for ints) right here.
  inject(0) { |sum, n| sum + n.to_i }

只需将其移动到 Array

的实例方法
class Array
  # whereas in your other method you send `inject` to an array you created, 
  # here you're sending it to *this* array instance `self`, which is the 
  # implicit target of instance methods. `self.inject` would be equivalent.
  def sum
    inject(0) {|sum, n| sum + n.to_i }
  end
end

然后您可以使用它来重构现有的 Integer#digit_sum

class Integer
  def digit_sum
    to_s.split("").sum
  end
end

现在用你在这里学到的知识来编写第二个方法。

class Array
  # There are plenty of ways to accomplish the task here, but for the sake
  # of pedagogy let's use the method you already wrote yourself.
  # This (rather fragile) method would assume you have an array of objects
  # that respond to `digit_sum`
  def sum_up_digit_sums
    # Exactly like plain `sum` but now we're using the other method you wrote,
    # `digit_sum` to determine the value instead of `to_i`
    inject(0) {|sum, n| sum + n.digit_sum }
  end
end