Unique values in hash?

V

Vapor ..

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.
 
R

Robert Klemme

2008/12/16 Vapor .. said:
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
 
R

Rupert Voelcker

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
 
D

David A. Black

Hi --

2008/12/16 Vapor .. said:
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
;-)

hash.invert.keys # :)


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,184
Messages
2,570,978
Members
47,561
Latest member
gjsign

Latest Threads

Top