Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to `Array::sample` for hashes?

Tags:

random

ruby

hash

I'm looking to extract n random key-value pairs from a hash.

like image 965
ryanVincent Avatar asked Mar 16 '13 20:03

ryanVincent


People also ask

How do you turn an array into a hash?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

What is hash array?

An array of hashes is useful when you have a bunch of records that you'd like to access sequentially, and each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures in this chapter.

How do you hash an array in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

How do you know if two hashes are equal?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared. Returns true if other is subset of hash.


2 Answers

Hash[original_hash.to_a.sample(n)] 

For Ruby 2.1,

original_hash.to_a.sample(n).to_h 
like image 151
sawa Avatar answered Sep 24 '22 04:09

sawa


I don't know of such method. Still you can do something like:

h[h.keys.sample] 

If you need to sample more than one element the code will have to be a bit more complicated.

EDIT: to get key value pairs instead of only the value you can do something like:

keys_sample = h.keys.sample(n) keys_sample.zip(keys_sample.map{|k| h[k]) 
like image 38
Ivaylo Strandjev Avatar answered Sep 21 '22 04:09

Ivaylo Strandjev