So for example for the array
nums = [1,2,3,4,5,6,7,8,9]
the result should be 384. One way of doing it and it comes immediately to most ruby developers is by combining methods and do it one liner. So for example this one would work nums.select(&:even?).inject(:*)
and seems very elegant. But there is a catch here. Even though it works, it does two loops so it isn't optimized. More specifically the above is O(2n) but it can be written with one loop and become O(n). Can you think, how?
Still one liner and using
reduce
(it is the same with inject
) you can write it like:nums.reduce(1) {|sum, num| num.even? ? num * sum : sum }
.
Ruby aliases
inject
and reduce
methods as many others to make it intuitive to developers.
How would you do it?