Recently I solved a problem on HackerRank requiring that I calculate and print the sum of the elements in an array. One way of getting the answer would be using each
like below:
a = [1, 2, 3]sum = 0
a.each do |i|sum += iendsum=> 6
Considering that the elements inside the array above aren’t complicated, the code snippet can be shortened to a more simplistic level by using these methods: sum
or inject
.
Sum
According to Ruby-Doc.org, this method returns the sum of elements in an enumerable. It continues to say that if a block is given, it is applied to each element before addition. The syntax goes as follows:
enumerable.sum { | obj| block }
So if we use the example from earlier, it should look like this:
a.sum { |i| sum + i }=> 6
As you can see, it looks so much cleaner and of course, you still get the same result.
Inject
According to Ruby-Doc.org, this method combines all the elements of the enumerable by applying binary operations, such as +, —, *, and /
. It is then specified by either a block or symbol that names a method or operator. The syntax goes as follows:
enumerable.inject (inital_value) { |result, obj| block }
So if we again use the example above, it should look like this:
a.inject { |sum, i| sum + i }=> 6
Yet again, we have cleaner code by using another built-in method.
Feel free and comment, share and check out some of the resources posted below. Thanks for reading!