Coming from JavaScript, I was not expecting Ruby’s Enumerable module to have methods for selecting min and max values from a collection. Especially with an added parameter that lets you “take” a range starting from zero.

For comparison, what if we needed the lowest x number of values from an array of numbers.

In JavaScript we’d sort numerically (requiring the conspicuous umbrage a declaring for the umpteenth time a comparison function) and then destructuring out the result.

function twoLowest(numbers) {
  return numbers
	.sort((a, b) => a - b)
	.slice(0, 2)
	.reduce((a, b) => a + b, 0);
}

Anyway, written in 10 days.

Matz giving us many ways to do things.

I want to make Ruby users free. I want to give them the freedom to choose. People are different.

From:

🔗 The Philosophy of Ruby: A Conversation with Yukihiro Matsumoto, Part I

def two_lowest(numbers)
  numbers.min(2).sum
end

Enumerable methods that can receive an operator as symbol. Glacial autumn breeze whipped up from the 101. I don’t have a brevity fetish, like I know many of you do. Or the tendency to place the one-liner upon the highest of pedestal. It’s the obvious natural-language-style readability of the Ruby here that is simply remarkable.

Achieving this is possible in JavaScript with more fanfare. But, alas, the maintenance cost of dressing up our array in Ruby’s fast casual couture.

class NumberArray {
  constructor(numbers) {
    this.value = numbers;
  }

  min(n) {
	function compareNumbers(a, b) {
	  return a - b
   }
   this.value = this.value.sort(compareNumbers).slice(0, n);
   return this;
  }

  sum() {
	function add(a, b) {
     return a + b
	}
    return this.value.reduce(add, 0);
  }
}

function twoLowest(numbers) {
  return new NumberArray(numbers).min(2).sum();
}