DEV Community

Kasia Ekiert
Kasia Ekiert

Posted on

Usage of method reduce in Ruby

Usage of reduce in ruby and a task:
Write a program that displays the sum of predecessors for the next 10 natural numbers. Expected result: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55.

My solution:

def counter(n)
  sum = 0 
  letters = []
  (1..n).each do |number|
    sum += number
    letters << sum
  end
  letters.join(", "). #remember to create an array first and then to join letters inside
end 

puts counter(10) #result: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55
Enter fullscreen mode Exit fullscreen mode

Tests:

require './training1'

RSpec.describe '#counter' do
  subject { counter(n) }

  context 'It gives partial sums of the numbers' do
    let(:n) { 10 }

    it "should return a line of numbers" do
      expect(subject).to eq("1, 3, 6, 10, 15, 21, 28, 36, 45, 55")
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

But if we don’t need to display all numbers and we need just a sum of them, we may use the method reduce:


def counter(n)
  (1..n).reduce(:+) 
end 

puts counter(10) #result: 55
Enter fullscreen mode Exit fullscreen mode

https://apidock.com/ruby/Enumerable/reduce

Enjoy :)

Top comments (0)