Ruby:使用哈希数组从另一个哈希数组中选择值

时间:2017-03-15 15:38:00

标签: arrays ruby hash

假设我有两个哈希数组:

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"}]

1 个答案:

答案 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"}]