I was getting my head around the reduce method (also known as inject) in Ruby for some code I am writing. I suspected that this would be what I really wanted to use with my array instead of the more generic each which first sprang to mind.
So I was eager to try out the concept with reduce and ready to code a quick separate sketch of the outline for my particular use case. However, most examples of reduce out there are mathematical in nature and this makes it harder to mentally translate to string use examples.
In my case, I'm using the string to stand in for a more complex data structure, so I didn't want to have to mentally translate from numbers to strings to higher order structures.
The Ruby documentation for reduce/inject was thorough but I struggled to wrap my head around their terminology, especially the word "memo". I finally realized that "memo" simply means the changing result. That seemed to do the trick mentally.
Since most of the functions in my particular project return the updated state of a data structure, that (the data structure) is generally what I want to be passing as "memo". So here is my code, so that I can find it easily if I need to refer to it again:
def changetext(startstr, addeditem)
startstr + addeditem
end
arr1 = ["a", "b", "c", "d", "e", "f", "g"]
str1 = "Abstract"
newstring = arr1.reduce(str1){|changing, arritem| changetext(changing, arritem)}
puts newstring
This code displays:
Abstractabcdefg
More info
The str1 as the parameter in arr1.reduce indicates the initial value of the changing result.
The changing parameter in the block could really be called anything, but I liked calling it changing to make it clear to myself that it gets updated with each application of an array item. And to put it together, changing should be thought of as "the thing that started out as str1 but got changed along the way".
Funnily enough, once I got my head around using reduce in this way, I tried as an exercise to compare it with an implementation using each instead for the sake of comparison, but now I couldn't figure out how to do it with each any more!
Further reading
James Hughes, 2017. Using the 'reduce' method in Ruby at Medium.com
D. Flaherty. Getting to know Ruby's Map and Reduce at flats.github.io