使用数组方法

时间:2015-01-10 17:39:07

标签: ruby arrays

在我的作业中,我必须为Integer类创建一个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

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

class Array
   def sum
       #Code
   end
end

数组有变量,我不知道如何将这些变量包含到我的代码中。我希望有人可以解释我应该如何使用它。

2 个答案:

答案 0 :(得分:1)

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. 创建一个字符数组
  4. .map(&:to_i)会在每个字符to_i上调用["1", "2", "1", "3", "1", "4"] => [1, 2, 1, 3, 1, 4](此时,如果您有任何单词字符,它们会变为零)
  5. 然后简单地用.reduce(:+)对所有内容求和(reduce是别名inject

答案 1 :(得分:0)

让我们从第二个方法开始,一个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