Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the reduce method work here?

Tags:

ruby

I read through the ruby docs examples but I'm still not sure what is happening in this code:

sentence = "How are you?"
sentence.chars.reduce do |memo, char|
    %w[a e i o u y].include?(char) ? memo + char * 5 : memo + char
end

What is the memo when the block of code is first executed? What do the subsequent 5 steps look like?

like image 944
Fralcon Avatar asked Dec 04 '25 13:12

Fralcon


1 Answers

Since you didn't provide a default value for reduce, it will set memo to be the first value in sentence.chars, which is "H".

Iteration #1:

  • memo is "H"
  • char is "o"
  • Result of the block is "Hooooo"

The result of the first iteration is then passed into the block as the first argument. So in iteration #2:

  • memo is "Hooooo"
  • char is "w"
  • Result of the block is "Hooooow"

This will continue for each element of the array and the end result will be the result of the block after it is applied to the last element.

A trivial way to see this in action is just executing the following code:

sentence = "How are you?"
sentence.chars.reduce do |memo, char|
  puts "Memo = #{memo}, char = #{char}"
  %w[a e i o u y].include?(char) ? memo + char * 5 : memo + char
end
like image 72
robbrit Avatar answered Dec 06 '25 10:12

robbrit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!