从Ruby中的数组数组中找到所需值的真正方法是什么?

Vas*_*kin 3 ruby arrays performance multidimensional-array

我在Ruby中有一个数组数组:

price_list = [
  ['Brand-1', 'Model-1', 100.00],
  ['Brand-1', 'Model-2', 200.00],
  ['Brand-2', 'Model-1', 10.00],
  ['Brand-2', 'Model-2', 20.00],
  ['Brand-1', 'Model-1', 110.00],
  ['Brand-1', 'Model-2', 190.00],
  ['Brand-1', 'Model-3', 300.00],
  ...
  ['Brand-n', 'Model-n', 1234.00]
]
Run Code Online (Sandbox Code Playgroud)

我需要创建只有独特产品和最低价格的新阵列.像这样的东西:

new_price_list = [
  ['Brand-1', 'Model-1', 100.00],
  ['Brand-2', 'Model-1', 10.00],
  ['Brand-2', 'Model-2', 20.00],
  ['Brand-1', 'Model-2', 190.00],
  ['Brand-1', 'Model-3', 300.00],
  ...
  ['Brand-n', 'Model-n', 1234.00]
]
Run Code Online (Sandbox Code Playgroud)

在Ruby中执行此操作的最快,最美的方法是什么?

tok*_*and 5

按键(品牌+型号)分组然后获得分组数组的最低价格:

prices = [
  ['Brand-1', 'Model-1', 100.00],
  ['Brand-1', 'Model-2', 200.00],
  ['Brand-2', 'Model-1', 10.00],
  ['Brand-2', 'Model-2', 20.00],
  ['Brand-1', 'Model-1', 110.00],
  ['Brand-1', 'Model-2', 190.00],
  ['Brand-1', 'Model-3', 300.00],
]

grouped = prices.group_by { |brand, model, price| [brand, model] }
grouped.values.map { |grouped_prices| grouped_prices.min_by(&:last) }
Run Code Online (Sandbox Code Playgroud)

输出:

[["Brand-1", "Model-2", 190.0],
 ["Brand-1", "Model-3", 300.0],
 ["Brand-2", "Model-1", 10.0],
 ["Brand-2", "Model-2", 20.0],
 ["Brand-1", "Model-1", 100.0]]
Run Code Online (Sandbox Code Playgroud)