Forum: Ruby Unique values in hash?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Vapor .. (Guest)
on 2008-12-16 10:55
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.
Robert K. (Guest)
on 2008-12-16 11:19
(Received via mailing list)
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
;-)

Cheers

robert
Rupert V. (Guest)
on 2008-12-16 11:20
(Received via mailing list)
> 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
Dan D. (Guest)
on 2008-12-16 12:18
(Received via mailing list)
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.
David A. Black (Guest)
on 2008-12-16 13:03
(Received via mailing list)
Hi --

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

>
> http://redhanded.hobix.com/bits/klemmeSSilentHash.html
> ;-)

hash.invert.keys   # :-)


David
This topic is locked and can not be replied to.