[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Unique values in hash?

Vapor ..

12/16/2008 8:48:00 AM

Hi,

I have a hash that contains duplicate data, for example, :username =>
"alex" comes many times.
I want to loop around and print their names just once (only unique). In
simple loop it would print "alex" repeatedly.

Thanks.
--
Posted via http://www.ruby-....

3 Answers

Robert Klemme

12/16/2008 9:11:00 AM

0

2008/12/16 Vapor .. <vaqas.ashraf@gmail.com>:
> I have a hash that contains duplicate data, for example, :username =>
> "alex" comes many times.
> I want to loop around and print their names just once (only unique). In
> simple loop it would print "alex" repeatedly.

irb(main):001:0> {:foo=>1,:bar=>1}.values.uniq
=> [1]

You can of course have more involved solutions, e.g. (shameless self promotion):

http://redhanded.hobix.com/bits/klemmeSSilen...
;-)

Cheers

robert

--
remember.guy do |as, often| as.you_can - without end

Rupert Voelcker

12/16/2008 9:13:00 AM

0

> I have a hash that contains duplicate data, for example, :username =>
> "alex" comes many times.
> I want to loop around and print their names just once (only unique). In
> simple loop it would print "alex" repeatedly.

hash.map { |k,v| v }.uniq.each { |name| puts name }

should do it

Rupert

David A. Black

12/16/2008 10:55:00 AM

0

Hi --

On Tue, 16 Dec 2008, Robert Klemme wrote:

> 2008/12/16 Vapor .. <vaqas.ashraf@gmail.com>:
>> I have a hash that contains duplicate data, for example, :username =>
>> "alex" comes many times.
>> I want to loop around and print their names just once (only unique). In
>> simple loop it would print "alex" repeatedly.
>
> irb(main):001:0> {:foo=>1,:bar=>1}.values.uniq
> => [1]
>
> You can of course have more involved solutions, e.g. (shameless self promotion):
>
> http://redhanded.hobix.com/bits/klemmeSSilen...
> ;-)

hash.invert.keys # :-)


David

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.r...
Coming in 2009: The Well-Grounded Rubyist (http://manning....)