我有一個散列數組,這不是活動記錄模型。此陣列屬於Person
類型的對象,屬性爲id
,name
,age
。我有第二個字符串數組,["john", "james", "bill"]
。與ID數組相交的散列陣列
我試圖刪除散列數組中的所有對象,除了那些在第二個數組中有名字的基本上執行相交的數據,但我遇到了很多問題。有什麼建議麼?我不確定我的語法是否剛剛關閉,或者我是否正在考慮這種錯誤的方式。顯然我可以迭代,但這似乎可能不是處理這種情況的最佳方式。
我有一個散列數組,這不是活動記錄模型。此陣列屬於Person
類型的對象,屬性爲id
,name
,age
。我有第二個字符串數組,["john", "james", "bill"]
。與ID數組相交的散列陣列
我試圖刪除散列數組中的所有對象,除了那些在第二個數組中有名字的基本上執行相交的數據,但我遇到了很多問題。有什麼建議麼?我不確定我的語法是否剛剛關閉,或者我是否正在考慮這種錯誤的方式。顯然我可以迭代,但這似乎可能不是處理這種情況的最佳方式。
http://www.ruby-doc.org/core-1.9.2/Array.html#method-i-select
arr1 = [{:id => 1, :name => "John"}, {:id => 2, :name => "Doe"}];
arr2 = ["Doe"];
intersect = arr1.select {|o| arr2.include? o[:name]} # you can also use select!
p intersect # outputs [{:name=>"Doe", :id=>2}]
我會提出一個'arr2'的設置,它可以消除O(n)的查找代價。 –
這正是我所尋找的。非常感謝。 – user1004031
遲到了,但如果ARR1:名字是一個數組這個工作很好:
arr1 = [{:id => 1, :name => ["John", "Doe"]}, {:id => 2, :name => ["Doe"]}];
arr2 = ["Doe"]
> intersect = arr1.reject{|o| (arr2 & o[:name]).empty?}
=> [{:id=>1, :name=>["John", "Doe"]}, {:id=>2, :name=>["Doe"]}] #output
> arr2 = ["John"]
> intersect = arr1.reject{|o| (arr2 & o[:name]).empty?}
=> [{:id=>1, :name=>["John", "Doe"]}] #output
或使用select:
intersect = arr1.select{|o| !(arr2 & o[:name]).empty?}
要刪除所有哈希陣列中的對象除了第二個數組中的名稱之外,您可以這樣做:
arr1.reject!{|o| (arr2 & o[:name]).empty?}
給出你的散列的一個例子 – apneadiving