How to Solve the Oxford Comma Challenge Using String Insertion and Replacement in Ruby

CodeTrouble blog
2 min readOct 19, 2022

--

Oxford Comma

One of the styles for writing sentences involves using the oxford comma. This is whereby the word “and” and any other conjunctions in a list of 3 or more words need to have a comma before them

"fiddleheads, okra, and kohlrabi"

On the other hand, another typical style involves no comma before the conjunction like so:

"fiddleheads, okra and kohlrabi"

So how do you implement a proper Oxford comma list or sentence when presented with an array of strings?

Problem with Solution

Given an array we should turn it into a string as highlighted below:

[“kiwi”, “durian”, “starfruit”, “mangos”, “dragon fruits”] => "kiwi, durian, starfruit, mangos, and dragon fruits"

Step 1: Insert

The first step involves adding and as an element in the array which we can accomplish using the insert method:

array.insert(-2, "and")

This method inserts “and” at the second last index of the array and returns a new array containing “and”

[“kiwi”, “durian”, “starfruit”, “mangos”, "and" “dragon fruits”]

Step 2: Join

Now that the word “and” is in the array, we can turn the array into a string using the join method:

str = array.join(", ")

Here we are setting a str variable with the newly created string.

The join method takes a separator, in which case we need to use a comma as our separator since our string should contain comma-separated words.

The separator also includes an extra space because each word in our string should be separated from the next word with a comma and one space. This is how our string would like:

“kiwi, durian, starfruit, mangos, and, dragon fruits”

Step 3: Replace using []=

The problem is that “and” contains a comma after it, which is not right, so we need to specifically change that part in our string.

That can be a process using other methods but luckily in Ruby, we can use the []= method to target a particular section in a string and change it.

In this case, we just need to select the target characters in our string and assign our replacement:

str["and,"]= "and"

Now every part in the string that had “and,” is replaced with just “and” the way the challenge expects.

The full function for the oxford comma looks like this below:

def oxford_comma(array)
if array.size == 1
array.join()
elsif array.size == 2
array.join(" and ")
else
array.insert(-2, "and")
str = array.join(", ")
str["and,"]= "and"
str
end
end

The first two if conditionals address cases where we have an array with just one or two words. In the case of two words, we only join the elements in the array with “ and ”.

You can read here to see what more you can do with []= method

--

--

CodeTrouble blog

A blog to help explain the technical issues that student developers face as they learn to code