如何从起点使用此reduce方法?

时间:2019-06-28 14:56:13

标签: ruby methods reduce

我已经尝试了一段时间了。这是一个红宝石课程,它要求您构建一种方法:

bubbles.forEach((bubble) => {
  bubble = "something";
})

到目前为止,这是我的代码,通过了第一个测试:

describe 'my own reduce-like methods' do
  describe "reduce_to_total returns a running total when not given a starting point" do
    it "reduces correctly" do
      source_array = [1,2,3]
      expect(reduce_to_total(source_array)).to eq(6)
    end
  end

  describe "reduce_to_total returns a running total when given a starting point" do
    it "reduces correctly" do
      source_array = [1,2,3]
      starting_point = 100
      expect(reduce_to_total(source_array, starting_point)).to eq(106)
    end
  end

但仍然出现以下错误:

def reduce_to_total(source_array, starting_point = 100)
    source_array.reduce(0) { |sum, num| sum + num}
end

感谢任何帮助/说明!谢谢

1 个答案:

答案 0 :(得分:1)

您需要将starting_point作为reduce参数传递

def reduce_to_total(source_array, starting_point = 0)
    source_array.reduce(starting_point) { |sum, num| sum + num}
end

参见下文:

[2] pry(main)> [1,2,3].reduce(0) { |sum, num| sum + num}
=> 6
[3] pry(main)> [1,2,3].reduce(100) { |sum, num| sum + num}
=> 106