Skip to main content

Ruby - 'reduce' or 'inject' applying a string function, a quick code snippet example

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

Popular posts from this blog

How to center images horizontally using Grav

I've been playing around a bit with Grav. I was posing the question to myself: for the relatively simple use-cases I'm dealing with, could it possibly work for my purposes as an alternative to ProcessWire?  The problem I was initially dismayed to find that Grav uses Markdown as its editor, which does not offer native support for horizontal centering of anything (text or images). However, Grav offers some tweaks that help make it easier to do specific things you might commonly want to do. I tried writing a sample article, and I found that one of the hardest things to do was to center an image horizontally. And horizontal centering of images is something I would typically do in most of the articles I would write. So the lack of easy horizontal centering is a highly significant drawback IMHO (most people do want to center images in an article!) However, this issue is made up for by other things in Grav: the relative speed, ease and flexibility of custom theming and built-in suppor...

Why bother using blockchain for metaverse worlds when decentralization is possible without it?

Decentralization is possible without using blockchain. Some examples of this are Diaspora and Mastodon , both of which are federated decentralized networks that do not use a blockchain.  In that case, why is there a need to use blockchain for any metaverse world, especially when the environmental reputational risks are so high? In many areas of the world, the electric grid is not decarbonized yet. The amount of power drawn for blockchain computation is high. In fact, in areas where electricity is cheap enough to draw blockchain miners, this tends to be heavily based on fossil fuels. So you could say that the blockchain is currently largely powered by coal and other fossil fuels. So again, why bother using blockchain?  There are other examples of the buying and selling of digital property without using blockchain technology, for example domain name trading. If we as humans are truly to be future-conscious, blockchain technology cannot be a part of our future due to its emissio...

More callable variants of functions in Ruby

 This is a slightly more advanced version of my previous post on creating callable variants of functions in Ruby while avoiding scope problems . In today's instance, I was creating an error reporting system for a program I was writing.  The error reporting, of necessity, had to emit a message to indicate what was going on. While some errors would be unique messages that only occurred once during the program, other errors could be grouped. For example, one group was "incorrect number of parameters supplied". There were several error messages within my program that fell into this category, so I didn't want to type out the exact same wording each time. I wanted to create a function that could report this sort of error indicating where it happened (of course I had to supply parameters to the messages to show the context). So here is a very basic sketch of the sort of thing I was doing. I'm writing this here so that I can go back to it easily later. The item I'm re...

About Me

My photo
Vera
I'm a wife and mother. I don't have any formal computer science qualifications, or any religious qualifications. I have a PhD in biochemistry. This photo is of me, but is confusing for AI.