假设我有两个哈希数组:
array_1 = [{name: "Dale Cooper", role: "author"},
{name: "Lucy Moran", role: "author"},
{name: "Harry Truman", role: "author"}]
array_2 = [{author: "Lucy Moran", title: "Lorem"},
{author: "Bobby Briggs", title: "Ipsum"},
{author: "Harry Truman", title: "Dolor"}]
如何从array_2
中选择array_1
中作者的哈希值?最好是结果如下:
array_3 = [{author: "Lucy Moran", title: "Lorem"},
{author: "Harry Truman", title: "Dolor"}]
答案 0 :(得分:3)
您可以保存集中的所有array_1
名称,以便从array_2
中选择哈希值:
require 'set'
array_1 = [{ name: 'Dale Cooper', role: 'author' },
{ name: 'Lucy Moran', role: 'author' },
{ name: 'Harry Truman', role: 'author' }]
array_2 = [{ author: 'Lucy Moran', title: 'Lorem' },
{ author: 'Bobby Briggs', title: 'Ipsum' },
{ author: 'Harry Truman', title: 'Dolor' }]
authors = Set.new(array_1.map{ |h| h[:name] })
array_3 = array_2.select{ |h| authors.include?(h[:author]) }
# [{:author=>"Lucy Moran", :title=>"Lorem"},
# {:author=>"Harry Truman", :title=>"Dolor"}]