Ruby 2.4根据可接受的键值列表拆分哈希数组

时间:2017-03-30 21:11:28

标签: ruby

我有一系列ID,如下所示:

printAdjacentNums('computation.csv', 0, 1)

我有一系列哈希。

ids = [101153, 87218, 99589, 73109, 80660, 107784, 76392, 101501]

如何从数组ID中过滤存在ID的哈希数组?

1 个答案:

答案 0 :(得分:2)

这不是很难。使用select对哈希进行迭代,以查看已知的ID。使用Set可以更快地查找。

require 'set'

ids = Set.new([101153, 87218, 99589, 73109, 80660, 107784, 76392, 101501])
hashes = [{"id"=>107786, "key"=>"ABC-2002", "hidden"=>true, "done"=>false},{"id"=>101501, "key"=>"ABC-2002", "hidden"=>true, "done"=>false},{"id"=>107786, "key"=>"ABC-2002", "hidden"=>true, "done"=>false},{"id"=>107784, "key"=>"ABC-2453", "hidden"=>true, "done"=>false},{"id"=>107786, "key"=>"ABC-1345", "hidden"=>true, "done"=>false}]

p hashes.select{ |h| ids.include?(h['id']) }
# [{"id"=>101501, "key"=>"ABC-2002", "hidden"=>true, "done"=>false}, {"id"=>107784, "key"=>"ABC-2453", "hidden"=>true, "done"=>false}]