Unique values in hash?

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-forum.com/.

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

···

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.

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

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

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.
--
Posted via http://www.ruby-forum.com/.

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

hash.invert.keys # :slight_smile:

David

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