2016-09-21 6 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

引用符btwを修正しました。今では無効なルビコードです。ここにはオブジェクトがあります:) –

+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の組み合わせを維持します。

幸せなルビーコーディングを手伝ってくれることを願っています!

+0

argh ...私の例をあまりにも単純にしたかもしれません...もしも、所有者のIDがあれば、fooはこれになります: 'foo = [{id:1、name: 'Eric Cartman '、メール:' [email protected] '}、 {ID:2、名前:' Eric Cartman '、メール:' [email protected] '}、 {id:3、名前: "カートマンのお母さん"、メール: '[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 

、「ブロックが与えられた場合、それは比較のために、ブロックの戻り値を使用します。」

関連する問題