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

D

D. Krmpotic

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
 
A

Alex Young

D. Krmpotic said:
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
 
R

Rick DeNatale

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.
 

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

Forum statistics

Threads
474,239
Messages
2,571,195
Members
47,831
Latest member
ClaudiaSig

Latest Threads

Top