如何在ruby中给出这些键的哈希值?

时间:2013-04-30 22:41:11

标签: ruby arrays sorting hash

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

{
  '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”位置将Hash转换为位置args数组。像这样。

[
  '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']

注意:

无法保证密钥的顺序正确。例如,上面的哈希可能在'arg4'之前有'arg9'“。很抱歉没有说清楚。

3 个答案:

答案 0 :(得分:5)

 h.sort_by { | a, _ | a.gsub(/[^\d]/, '').to_i }.map(&:last)

答案 1 :(得分: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"]

答案 2 :(得分:0)

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