2016-09-21 16 views
-1

可以說我擁有一個包含多個電子郵件和名稱哈希的數組。例如,我有這樣的事情:如何將.uniq與哈希用於唯一對?

foo = [{id: 1, name: 'Eric Cartman', email: '[email protected]'}, 
     {id: 2, name: 'Eric Cartman', email: '[email protected]'}, 
     {id: 3, name: "Cartman's mom", email: '[email protected]'}, 
     {id: 4, name: 'Eric Cartman', email: '[email protected]'}] 

如何使用.uniq返回基於姓名和電子郵件的結合獨特的價值?例如,我想回到這樣的事情:

[{id: 1, name: 'Eric Cartman', email: '[email protected]'}, 
{id: 2, name: 'Eric Cartman', email: '[email protected]'}, 
{id: 3, name: "Cartman's mom", email: '[email protected]'}] 
+2

修復引號,順便說一句。現在它是無效的紅寶石代碼和一些人在這裏_will_對象:) –

+1

你跟着@ Sergio的建議來修復報價,但你仍然有單引號和雙引號的混合。這冒犯了我的感情,所以我反對! –

回答

2

foo.uniq應該只是罰款。 由於

{name: "cartman", email: "[email protected]"} == {name: "cartman", email: "[email protected]"} # => True 
{name: "stan", email: "[email protected]"} == {name: "cartman", email: "[email protected]"} # => False 

==操作檢查,如果哈希的各個領域有相同的價值觀。所以.uniq將工作你想如何工作!

如果不是隻你應該用塊使用uniq方法的電子郵件,姓名等領域更多:

foo.uniq { |x| [x[:name], x[:email]] } 

這將僅保留名稱和電子郵件的uniq的組合。

希望它有幫助,快樂的ruby編碼!

+0

argh ...我可能讓我的例子太簡單了...如果在has中有一個id,那麼foo會是這樣的: 'foo = [{id:1,name:'Eric Cartman ',email:'[email protected]'}, {id:2,name:'Eric Cartman',email:'[email protected]'}, {id:3,name:「Cartman's mom」,電子郵件:'[email protected]'}, {id:4,名稱:'Eric Cartman',電子郵件:'[email protected]'}]' –

+1

有沒有必要公佈編輯的答案和大膽的臉是既不需要也不吸引人。如果您想改進或希望實施其他人提出的建議,我建議您簡單地重寫您的答案。把它堆到你以前寫的東西只是一個分心。像書本或博客那樣寫答案,修改是正常的。 –

2

Array#uniq需要一個塊:

foo = [{id: 1, name: 'Eric Cartman', email: '[email protected]'}, 
     {id: 2, name: 'Eric Cartman', email: '[email protected]'}, 
     {id: 3, name: "Cartman's mom", email: '[email protected]'}, 
     {id: 4, name: 'Eric Cartman', email: '[email protected]'}] 

bar = foo.uniq {|h| [h[:name], h[:email]] } 

bar == [{id: 1, name: 'Eric Cartman', email: '[email protected]'}, 
     {id: 2, name: 'Eric Cartman', email: '[email protected]'}, 
     {id: 3, name: "Cartman's mom", email: '[email protected]'}] #=> true 

每文檔,「如果一個塊給出,其將使用塊的返回值進行比較。」