假設
我假定:
在兩個
new_data
一個
old_data
的
"name"
的值是唯一的
- ;
new_data
是包含一個鍵值對的散列數組;和
old_data
是包含至少兩個鍵值對的散列數組。
代碼
def extract_elements(new_data, old_data)
(new_data+old_data).group_by { |h| h["name"] }.
values.
select { |a| a.size > 1 || a.first.size == 1 }.
map(&:last)
end
例
new_data = [{"name" => "a"}, {"name" => "b"}, {"name" => "c"}]
old_data = [{"name" => "a", "data" => "extra1"},
{"name" => "d", "data2" => "extra"}]
extract_elements(new_data, old_data)
#=> [{"name"=>"a", "data"=>"extra1"}, {"name"=>"b"}, {"name"=>"c"}]
說明
對於上面的例子:
a = (new_data+old_data)
#=> [{"name"=>"a"}, {"name"=>"b"}, {"name"=>"c"},
# {"name"=>"a", "data"=>"extra1"}, {"name"=>"d", "data2"=>"extra"}]
b = a.group_by { |h| h["name"] }
#=> {"a"=>[{"name"=>"a"}, {"name"=>"a", "data"=>"extra1"}],
# "b"=>[{"name"=>"b"}],
# "c"=>[{"name"=>"c"}],
# "d"=>[{"name"=>"d", "data2"=>"extra"}]}
c = b.values
#=> [[{"name"=>"a"}, {"name"=>"a", "data"=>"extra1"}],
# [{"name"=>"b"}],
# [{"name"=>"c"}],
# [{"name"=>"d", "data2"=>"extra"}]]
d = c.select { |a| a.size > 1 || a.first.size == 1 }
#=> [[{"name"=>"a"}, {"name"=>"a", "data"=>"extra1"}],
# [{"name"=>"b"}],
# [{"name"=>"c"}]]
e = d.map(&:last)
#=> [{"name"=>"a", "data"=>"extra1"},
# {"name"=>"b"},
# {"name"=>"c"}]
限制性條款
這需要Ruby V1.9 +,因爲它需要被保持的哈希b
鑰匙插入順序。對於早期版本,替換:
map(&:last)
有:
map { |h| h.max_by(&:size) }
有趣,但你做了很多工作,爲new_data'的'每個元素。我認爲最好先爲'old_data'構造一個查找哈希(就像@tadman爲'old_data'完成的那樣。 –
謝謝,我喜歡! – andreofthecape