Home > Back-end >  Ruby's array min returning value, not array
Ruby's array min returning value, not array

Time:12-16

In Ruby (3.0.1) the min function on an array

Returns one of the following:

  • The minimum-valued element from self.
  • A new Array of minimum-valued elements selected from self.

(from here).

So, given

l = [{n: 1, m: 6}, {n: 1, m: 5}, {n: 2, m: 4}, {n: 3, m: 3}, {n: 4, m: 3}]

I would expect

l.min { |a, b| a[:n] <=> b[:n] }
=> [{:n=>1, :m=>6}, {:n=>1, :m=>5}]

but instead I get

l.min { |a, b| a[:n] <=> b[:n] }
=> {:n=>1, :m=>6}

Why? Why am I getting one of the list of the minimal elements rather than the entire list of minimal elements?

CodePudding user response:

If you read the rest of the specification:

With no argument and (a block/no block), returns the element in self having the minimum value per (the block/method <=>):

The only case when it returns more than one element is if you specify the number of elements that you want returned:

With an argument n and (a block/no block), returns a new Array with at most n elements, in ascending order per (the block/method <=>):

[0, 1, 2, 3].min(3) # => [0, 1, 2]
  • Related