# Getting a n-th key-value pair from a hash

**URL:** <https://www.ruby-forum.com/t/getting-a-n-th-key-value-pair-from-a-hash/89882>\
**Category:** Ruby\
**Created:** [March 23, 2007, 2:40pm UTC](https://www.ruby-forum.com/t/getting-a-n-th-key-value-pair-from-a-hash/89882 "2007-03-23T14:40:36Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![dxk3355](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/d6d6ee/32.png) [@dxk3355](https://www.ruby-forum.com/u/dxk3355)\
**Post date:** [March 23, 2007, 2:40pm UTC](https://www.ruby-forum.com/t/getting-a-n-th-key-value-pair-from-a-hash/89882/1 "2007-03-23T14:40:36Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dxk3355](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/d6d6ee/32.png) [@dxk3355](https://www.ruby-forum.com/u/dxk3355)\
**Post date:** [March 23, 2007, 2:48pm UTC](https://www.ruby-forum.com/t/getting-a-n-th-key-value-pair-from-a-hash/89882/2 "2007-03-23T14:48:49Z")

</div>

D. Krmpotic wrote:

> 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

---

<div class="post-metadata">

**Author:** ![dxk3355](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/d6d6ee/32.png) [@dxk3355](https://www.ruby-forum.com/u/dxk3355)\
**Post date:** [March 23, 2007, 2:49pm UTC](https://www.ruby-forum.com/t/getting-a-n-th-key-value-pair-from-a-hash/89882/3 "2007-03-23T14:49:49Z")

</div>

On 3/23/07, D. Krmpotic [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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.denhaven2.com/](http://talklikeaduck.denhaven2.com/)

---

<div class="post-metadata">

**Author:** ![dxk3355](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/d6d6ee/32.png) [@dxk3355](https://www.ruby-forum.com/u/dxk3355)\
**Post date:** [March 23, 2007, 3:12pm UTC](https://www.ruby-forum.com/t/getting-a-n-th-key-value-pair-from-a-hash/89882/4 "2007-03-23T15:12:32Z")

</div>

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