Unique values in hash?


#1

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.


#2

2008/12/16 Vapor … removed_email_address@domain.invalid:

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/klemmeSSilentHash.html
:wink:

Cheers

robert


#3

h=Hash[*%w(a alex b mary c alex).flatten]
=> {“a”=>“alex”, “b”=>“mary”, “c”=>“alex”}

irb(main):014:0> h.values
=> [“alex”, “mary”, “alex”]

irb(main):015:0> h.values.uniq
=> [“alex”, “mary”]

— On Tue, 12/16/08, Vapor … removed_email_address@domain.invalid wrote:
From: Vapor … removed_email_address@domain.invalid
Subject: Unique values in hash?
To: “ruby-talk ML” removed_email_address@domain.invalid
Date: Tuesday, December 16, 2008, 3:48 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.


#4

Hi –

On Tue, 16 Dec 2008, Robert K. wrote:

http://redhanded.hobix.com/bits/klemmeSSilentHash.html
:wink:

hash.invert.keys # :slight_smile:

David


#5

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