有条件地从哈希数组中提取哈希值

时间:2015-08-26 11:18:58

标签: arrays ruby hash

从以下哈希数组:

x = [
  {"creationDate"=>123456,"createdBy"=>"test_user1"},
  {"creationDate"=>123459,"createdBy"=>"test_user1"},
  {"creationDate"=>123458,"createdBy"=>"test_user1"},
  {"creationDate"=>123454,"createdBy"=>"test_user2"},
  {"creationDate"=>123452,"createdBy"=>"test_user2"},
  {"creationDate"=>123451,"createdBy"=>"test_user2"}
]

我正在尝试查找:creationDate值为:createdBy的最大"test_user1"值。我这样做了:

x.map {|a| a['creationDate'] if a['createdBy'] == 'test_user1'}
# => [123456,123459,123458,nil,nil,nil]

我想摆脱nil,以便我可以将max应用于该数组。如何修改上面的代码?

5 个答案:

答案 0 :(得分:1)

您想要做的是:

x.select { |record| record[:createdBy] == 'test_user1' }.map { |record| record[:creationDate] }.max
  # => 123459

一般情况下,要从数组中删除nil,您只需拨打Array#compact

[1, nil, nil, 2, 'foo', nil].compact # => [1, 2, "foo"]

答案 1 :(得分:1)

它接近你打算在python中做的事情:

x.select { |n| n[:createdBy] == "test_user1" }.max_by { |n| n[:creationDate] }

第一个操作选择“test_user1”创建的记录,而第二个操作根据creationDate获取结果数组的最大值

答案 2 :(得分:0)

我猜是这样的:

x.delete_if {|x| x == nil}

答案 3 :(得分:0)

这是地图缩减功能的理想选择,例如inject

x = [{"creationDate" => 123456,"createdBy" => "test_user1"},
     {"creationDate" => 123459,"createdBy" => "test_user1"},
     {"creationDate" => 123458,"createdBy" => "test_user1"},
     {"creationDate" => 123454,"createdBy" => "test_user2"},
     {"creationDate" => 123452,"createdBy" => "test_user2"},
     {"creationDate" => 123451,"createdBy" => "test_user2"}]

x.inject(nil) do |result, item|
  if item["createdBy"] == "test_user1" && (result.nil? or item["creationDate"] > result)
    item["creationDate"]
  else
    result
  end
end

这是inject的可能实现。该块将迭代集合中的每个项目,并始终保持最高值。

答案 4 :(得分:0)

isset()
 if(isset($_GET['ahosts']))