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.
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.
2008/12/16 Vapor … [email protected]:
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
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 … [email protected] wrote:
From: Vapor … [email protected]
Subject: Unique values in hash?
To: “ruby-talk ML” [email protected]
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.
Hi –
On Tue, 16 Dec 2008, Robert K. wrote:
hash.invert.keys # ![]()
David
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs