[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

getting a n-th key-value pair from a hash

David Krmpotic

3/23/2007 1:41:00 PM

Hi!

suppose I have this hash:

data = { "a" => 1, "b" => 2, "c" => 3 }

I'd like to get a random pair from the hash.

so

data.get_pair(data.rand)

should return ["b", 2] for example.

How could this be done? I cannot find any method in the documentation.

Thank You!

david

--
Posted via http://www.ruby-....

3 Answers

Alex Young

3/23/2007 1:48:00 PM

0

D. Krmpotic wrote:
> Hi!
>
> suppose I have this hash:
>
> data = { "a" => 1, "b" => 2, "c" => 3 }
>
> I'd like to get a random pair from the hash.
>
> so
>
> data.get_pair(data.rand)
>
> should return ["b", 2] for example.
>
> How could this be done? I cannot find any method in the documentation.

class Hash
def get_rand_pair
key = self.keys[rand(self.length)]
[key, self[key]]
end
end

--
Alex

Rick DeNatale

3/23/2007 1:49:00 PM

0

On 3/23/07, D. Krmpotic <david.krmpotic@gmail.com> wrote:
> Hi!
>
> suppose I have this hash:
>
> data = { "a" => 1, "b" => 2, "c" => 3 }
>
> I'd like to get a random pair from the hash.
>
> so
>
> data.get_pair(data.rand)
>
> should return ["b", 2] for example.
>
> How could this be done? I cannot find any method in the documentation.
>
> Thank You!
>
> david

class Hash

def random_pair
to_a[rand(size)]
end
end

Note that what you asked for here is not getting the n-th pair as your
title suggests. That's problematical with a hash since hashes have no
defined ordering.

But to get a random key-value pair this should work.
--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denh...

David Krmpotic

3/23/2007 2:13:00 PM

0

Great! Thank you both.. didn't think of those simple solutions.

--
Posted via http://www.ruby-....