以数组作为键的哈希,如何通过哈希中的第一个值获取

时间:2016-03-10 14:11:09

标签: arrays ruby hash group-by fetch

我有一个用group_by创建的分组哈希,它创建一个数组作为键:

 @lines.group_by{|e| [e.activity, e.subactivity]}

因此,我的结果哈希看起来像这样:

{[7, 6]=>
  [{:field_one=>"AAA",
    :field_two=>"BBB",
    :activity=>7,
    :subactivity=>6}],
 [1,0] =>
  [{:field_one=>"CCC",
    :field_two=>"DDD",
    :activity=>1,
    :subactivity=>0}],
 [1,7] =>
  [{:field_one=>"EEE",
    :field_two=>"FFF",
    :activity=>1,
    :subactivity=>7}],
}

我想获得一个包含[1, *]等键的所有值的数组。所以,结果将是:

  [{:field_one=>"CCC",
    :field_two=>"DDD",
    :activity=>1,
    :subactivity=>0},
   {:field_one=>"EEE",
    :field_two=>"FFF",
    :activity=>1,
    :subactivity=>7}]

我该怎么做?

4 个答案:

答案 0 :(得分:1)

h.select { |(f,_),v| f==1 }.values

h.values_at(*h.keys.select { |f,_| f==1 })

如果键是一个或多个元素的数组,可能大小不一,但你只关心第一个元素(如此处),你会写:

h.select { |(f,*_),v| f==1 }.values

或只是

h.select { |(f,*),v| f==1 }.values

答案 1 :(得分:0)

也许这会有所帮助。

<强>输入

h = {
  [7, 6] =>
    [
      {:field_one => "AAA",
       :field_two => "BBB",
       :activity => 7,
       :subactivity => 6}
    ],
  [1, 0] =>
    [
      {:field_one => "CCC",
       :field_two => "DDD",
       :activity => 1,
       :subactivity => 0}
    ],
  [1, 7] =>
    [
      {:field_one => "EEE",
       :field_two => "FFF",
       :activity => 1,
       :subactivity => 7}
    ],
}

<强>码

h.keys.group_by { |a| a[0] }.each_with_object({}) do |(k, keys), exp| 
  exp[k] = keys.map { |key| h[key] }.flatten 
end

<强>输出

{
  7 => [
    {:field_one => "AAA", :field_two => "BBB", :activity => 7, :subactivity => 6}
  ],
  1 => [
    {:field_one => "CCC", :field_two => "DDD", :activity => 1, :subactivity => 0},
    {:field_one => "EEE", :field_two => "FFF", :activity => 1, :subactivity => 7}
  ]
}

答案 2 :(得分:0)

如果任何密钥可以包含数字1,请使用#include?

vals.select { |k, _v| k.include?(1) }.values.flatten
=> [{:field_one=>"CCC", :field_two=>"DDD", :activity=>1, :subactivity=>0}, {:field_one=>"EEE", :field_two=>"FFF", :activity=>1, :subactivity=>7}]

或者,如果密钥中的第一个值必须是1,那么:

vals.select { |k, _v| k[0] == 1 }.values.flatten
=> [{:field_one=>"CCC", :field_two=>"DDD", :activity=>1, :subactivity=>0}, {:field_one=>"EEE", :field_two=>"FFF", :activity=>1, :subactivity=>7}]

答案 3 :(得分:0)

假设h是你的哈希值,那么:

arr = []
h.each do |k,v|
   arr << v if k.first == 1
end