← Back to writing
Ruby 1 min read

Quick ruby tip: Interview simple question

We examine a simple question regarding ruby and how to write efficient code

I've asked in the past a question in an interview and I thought to add it here. The question was: Given an array of integers, multiply the even numbers.

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?
Keep reading

Quick tip: Docker compose network with docker port binding

Not a secret but a common network issue to look when you setup a new project

Next article →