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.
9f6e775366f2f607647fab8eeed66507?d=identicon&s=25 Vapor .. (vapor)
on 2008-12-16 09: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.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2008-12-16 10:19
(Received via mailing list)
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/klemmeSSilentHash.html
;-)

Cheers

robert
Fb1fc6f2eccd067a19b298d89235bfe0?d=identicon&s=25 Rupert Voelcker (rupert)
on 2008-12-16 10: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
Ad97b577f331ae29ed90da5751f2e44f?d=identicon&s=25 Dan Diebolt (dandiebolt)
on 2008-12-16 11: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 .. <vaqas.ashraf@gmail.com> wrote:
From: Vapor .. <vaqas.ashraf@gmail.com>
Subject: Unique values in hash?
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
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.
F53b05cdbdf561cfe141f69b421244f3?d=identicon&s=25 David A. Black (Guest)
on 2008-12-16 12:03
(Received via mailing list)
Hi --

On Tue, 16 Dec 2008, Robert Klemme wrote:

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

hash.invert.keys   # :-)


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