Ruby的数组最小返回值,不是数组

Ruby's array min returning value, not array

在 Ruby (3.0.1) 中,数组上的 min 函数

Returns one of the following:

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

(来自 here)。

所以,给定

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

我希望

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

但我得到

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

为什么?为什么我得到的是最小元素列表之一,而不是整个最小元素列表?

如果您阅读了规范的其余部分:

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

唯一 returns 多个元素的情况是指定要返回的元素数:

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]