[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

distinct

jney

4/12/2007 3:55:00 PM

hello,

a little question... how to get distinct values from an hash?

ex:
hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
==> hash_with_distinct_values = [100, 200]

thanks.

4 Answers

Alex Young

4/12/2007 3:57:00 PM

0

Jean-Sébastien wrote:
> hello,
>
> a little question... how to get distinct values from an hash?
>
> ex:
> hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
> ==> hash_with_distinct_values = [100, 200]
hash.values.uniq is the simplest.

--
Alex

Brian Candler

4/12/2007 6:21:00 PM

0

On Fri, Apr 13, 2007 at 12:55:06AM +0900, Jean-S?bastien wrote:
> a little question... how to get distinct values from an hash?
>
> ex:
> hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
> ==> hash_with_distinct_values = [100, 200]

irb(main):001:0> hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
=> {"a"=>100, "b"=>200, "d"=>200}
irb(main):002:0> hash.invert.keys
=> [100, 200]

jg.ruby

4/12/2007 7:09:00 PM

0

On Apr 12, 11:54 am, "Jean-Sébastien" <jeansebastien....@gmail.com>
wrote:
> hello,
>
> a little question... how to get distinct values from an hash?
>
> ex:
> hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
> ==> hash_with_distinct_values = [100, 200]
>
> thanks.

irb(main):001:0> hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
=> {"a"=>100, "b"=>200, "d"=>200}
irb(main):002:0> hash.values.uniq
=> [100, 200]

Robert Dober

4/12/2007 7:33:00 PM

0

On 4/12/07, Brian Candler <B.Candler@pobox.com> wrote:
> On Fri, Apr 13, 2007 at 12:55:06AM +0900, Jean-S?bastien wrote:
> > a little question... how to get distinct values from an hash?
> >
> > ex:
> > hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
> > ==> hash_with_distinct_values = [100, 200]
>
> irb(main):001:0> hash = {"a"=>100, "b"=>200, "d"=>100, "d"=>200}
> => {"a"=>100, "b"=>200, "d"=>200}
> irb(main):002:0> hash.invert.keys
> => [100, 200]
>
>
I would have completely agreed with hash.values.uniq as the simplest
solution, but has.invert.keys is extremely surprising, thx Brian.

Robert


--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw