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
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
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
https://apidock.com/ruby/Enumerable/reduce
Enjoy :)
Top comments (0)