2016-09-22 83 views
-1

我有兩個紅寶石陣列。 source_array以散列形式包含我所有的源數據。我有一個user_array包含用戶選擇的數據的子集。我需要合併/合併這兩個數組,以形成一個新的result_array,保留user_array的所有哈希值,並從source_array中添加user_array中不存在的哈希值。添加從一個陣列到另一個丟失的哈希

源陣列:

source_array = [ 
     {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>""}, 
     {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
     {:category=>"truck", :make=>"ford", :model=>"F350", :notes=>""}, 
     {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", :notes=>""} 
    ] 

目標數組:

target_array = [ 
    {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."} 
] 

結果數組:

result_array = [ 
     {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>""}, 
     {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
     {:category=>"truck", :make=>"ford", :model=>"F350", :notes=>""}, 
     {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."} 
    ] 

我明白任何幫助,您可以提供!

+1

Whar你有沒有試過? – philipp

+1

你有什麼是數組,而不是哈希(順便說一下,首先有無效的語法) –

+1

你需要編輯你的問題,以澄清你想要的。除此之外,爲您的示例顯示期望的結果將會有所幫助。另外,在你的例子中爲所有輸入對象賦值變量很有用(例如,source_arr = [{:category => ....}]'和'target_arr = [...]')。這樣,讀者可以在答案和評論中引用這些變量,而不必定義它們,所有讀者都會說同樣的變量。還有兩件事:將你的引用改爲「數組」,並在四個地方將':notes =「」'改爲':notes =>「」''。 –

回答

1

我們給出

source_arr = 
[ 
    {:category=>"truck", :make=>"ford", :model=>"F150", :notes=>""}, 
    {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
    {:category=>"truck", :make=>"ford", :model=>"F350", :notes=>""}, 
    {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", :notes=>""} 
] 

target_arr = 
[ 
    {:category=>"truck", :make=>"ford", :model=>"F150", 
    :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."}, 
    {:category=>"truck", :make=>"ford", :model=>"F350", :notes=>"what a beast!"} 
] 

首先構造一個哈希與將要匹配的鑰匙。

target_hashes = target_arr.map { |h| h.reject { |k,_| k == :notes } } 
    #=> [{:category=>"truck", :make=>"ford", :model=>"F150"}, 
    # {:category=>"truck", :make=>"ford", :model=>"F350"}] 

接下來構建包含在source_arr所有散列值不散列所有鍵匹配target_hashes陣列。

sources_to_add = source_arr.reject { |h| 
    target_hashes.include?(h.reject {|k,_| k == :notes }) } 
    #=> [{:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
    # {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", :notes=>""}] 

現在構建所需的數組。

target_arr + sources_to_add 
    #=> [{:category=>"truck", :make=>"ford", :model=>"F150", 
    #  :notes=>"Mileage 290 miles for a full tank of gas. Shortlist for now."}, 
    # {:category=>"truck", :make=>"ford", :model=>"F350", 
    #  :notes=>"what a beast!"}, 
    # {:category=>"truck", :make=>"ford", :model=>"F250", :notes=>""}, 
    # {:category=>"truck", :make=>"chevy", :model=>"Silverado 1500", 
    #  :notes=>""}] 

,如果你不希望修改target_arr

target_arr += sources_to_add 

如果你這樣做。

+0

謝謝!這正是我想要的。現在讓我試試看,我會更新回來。 –

相關問題