2

所以我有这个哈希。它看起来像这样:

{
  'arg0' => '126150656000',
  'arg1' => 'Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz',
  'arg2' => '2790',
  'arg3' => '3276320768',
  'arg4' => '8467496960',
  'arg5' => 'Windows 7',
  'arg6' => '6.1',
  'arg7' => 'amd64',
  'arg8' => '2',
  'arg9' => '1920',
  'arg10' => '1200',
  'arg11' => '32',
}

哈希需要根据键的 'argN' 位置转换为位置参数数组。像这样。

[
  '126150656000',
  'Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz',
  '2790',
  '3276320768',
  '8467496960',
  'Windows 7',
  '6.1',
  'amd64',
  '2',
  '1920',
  '1200',
  '32'
]

这里的目标是[0] == ['arg0'], [1] == ['arg1'], [N] == ['argN']

笔记:

不能保证键的顺序正确。例如,上面的哈希可能有“arg9”“之前”“arg4”。很抱歉没有说清楚。

4

3 回答 3

5
 h.sort_by { | a, _ | a.gsub(/[^\d]/, '').to_i }.map(&:last)
于 2013-04-30T22:55:55.217 回答
1

首先打乱你的哈希:

h = {
  'arg1' => 'Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz',
  'arg3' => '3276320768',
  'arg4' => '8467496960',
  'arg7' => 'amd64',
  'arg5' => 'Windows 7',
  'arg2' => '2790',
  'arg6' => '6.1',
  'arg9' => '1920',
  'arg8' => '2',
  'arg0' => '126150656000',
  'arg10' => '1200',
  'arg11' => '32',
}

你可以这样做:

h.keys.sort.map{|k| h[k]}
# => ["126150656000", "Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz", "1200",
#     "32", "2790", "3276320768", "8467496960", "Windows 7", "6.1",
#     "amd64", "2", "1920"]

更新:这是假设您希望您的键按标准排序顺序排序,如果它们是字面上'arg0''arg11',则不是您所期望的。我猜你的实际钥匙更有用。如果这些是您的实际密钥,您可能会这样做:

h.keys.sort_by{|s| s[3..-1].to_i}.map{|k| h[k]}
# => ["126150656000", "Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz", "2790",
#     "3276320768", "8467496960", "Windows 7", "6.1", "amd64", "2", "1920",
#     "1200", "32"]
于 2013-04-30T22:52:50.770 回答
0

如果哈希包含未排序的键,则提供的答案很好。根据您的示例,看起来它们已经订购了。如果是这种情况,那么您需要做的就是执行 {}.values 以获得值的“有序”数组。

于 2013-04-30T22:52:55.390 回答