Forum: Ruby getting a n-th key-value pair from a hash

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4057d36ea1505c263efbdbdc0bf511cd?d=identicon&s=25 D. Krmpotic (rubypassion)
on 2007-03-23 14:40
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
Ad7805c9fcc1f13efc6ed11251a6c4d2?d=identicon&s=25 Alex Young (regularfry)
on 2007-03-23 14:48
(Received via mailing list)
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
8f6f95c4bd64d5f10dfddfdcd03c19d6?d=identicon&s=25 Rick Denatale (rdenatale)
on 2007-03-23 14:49
(Received via mailing list)
On 3/23/07, D. Krmpotic <david.krmpotic@gmail.com> 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/
4057d36ea1505c263efbdbdc0bf511cd?d=identicon&s=25 D. Krmpotic (rubypassion)
on 2007-03-23 15:12
Great! Thank you both.. didn't think of those simple solutions.
This topic is locked and can not be replied to.