Why I love Ruby: An example

I was having fun doing an easy HackerRank challenge this morning. (The gist of the problem is, given an array like [4, 4, 3, 1, 2], return the number of times the maximum value occurs — in this case, 4 occurs twice so I would return 2.)

JavaScript:

function birthdayCakeCandles(ar) {
  var max = ar.reduce(function(a, b) {
  return Math.max(a, b);
  });
  var count = 0;
  for (var i = 0; i < ar.length; i++) {
    if(ar[i] === max) {
    count++;
    }
  };
  return count;
}

Ruby:

def birthday_cake_candles(ar)
  ar.count(ar.max)
end

Both of these solutions do exactly the same thing. It’s striking and just a little bit hilarious how much more elegant and simple Ruby is.

(If you have a one-line JavaScript solution that I’m missing, I’d love to see it!)

Like what you read? Give Jeremy Lenz a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.