Ruby: Inject/Reduce and the Ternary Operator

During our first code challenge this week, one of our deliverables was to provide an average star rating of a restaurant based on the reviews it already had. As with a lot aspects with coding, there’s so many different ways to end up at the same result, whether it be with the code itself or the enumerable that is used. For this deliverable, I ended up using the result below:

(code simplified to show without context of the whole challenge)

While this method works, there was another enumerable I could’ve used instead of “.sum,” which in the above code gets the sum of the ratings array. During lecture, it was mentioned that we can use this enumerable to calculate average, but I didn’t understand how it worked. On https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-inject, I reviewed the description for the enumerator, but could not wrap my head around:

After going it with my instructor during my feedback session, we went over this and found that the code below works just as well:

To break down the code block, the sum variable between the pipes is known as the accumulator or the memo. If sum is unassigned before the start of the iteration, it will take the value of the first element in the array. The n value at each iteration will take the value of the subsequent element in the array. Depending on the operation asked for in the code block, the accumulator/memo will be the value after the operation. This will continue until it iterates through the whole array. For the example above, it can be broken down like below:

To work in a way to assign sum as a number before the iteration starts, it would be written as below. The value assigned as the sum and the first element will begin as the value for n:

As this started to make sense, I noticed one extra example provided on https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-inject where it would tackle the longest word in an array of strings:

Finally understanding how inject/reduce works, I thought I’d be able to make sense of this, but I just couldn’t fully understand what “memo.length > word.length ? memo : word” meant! I got the gist that it’s comparing the length of two words, but I had no idea what everything meant after “?.” Doing more research, I found that it’s called the “ternary operator!” This operator works exactly like an if/else statements with “memo” returning if the conditional was true and “word” returning if the conditional was false. For example:

When using this in conjunction with inject/reduce, whatever is returned based off the conditional becomes the value of the accumulator/memo until the full array is iterated through. Therefore, “sheep” is returned as the longest word.

Software Engineer based out of the San Francisco Bay Area. Flatiron School graduate with 8+ years background in healthcare.