Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/rand.rb

Instance Method Summary collapse

Instance Method Details

#pickObject

Choose and return a random key-value pair of self.

{:one => 1, :two => 2, :three => 3}.pick  #=> [:one, 1]


117
118
119
120
# File 'lib/rand.rb', line 117

def pick
  k = keys.pick
  [k, self[k]]
end

#pick!Object

Deletes a random key-value pair of self, returning that pair.

a = {:one => 1, :two => 2, :three => 3}
a.pick  #=> [:two, 2]
a       #=> {:one => 1, :three => 3}


126
127
128
129
130
# File 'lib/rand.rb', line 126

def pick!
  rv = pick
  delete rv.first
  rv
end

#pick_keyObject

Return a random key of self.

{:one => 1, :two => 2, :three => 3}.pick_key  #=> :three


134
135
136
# File 'lib/rand.rb', line 134

def pick_key
  keys.pick
end

#pick_key!Object

Delete a random key-value pair of self and return the key.

a = {:one => 1, :two => 2, :three => 3}
a.pick_key!  #=> :two
a       #=> {:one => 1, :three => 3}


148
149
150
# File 'lib/rand.rb', line 148

def pick_key!
  pick!.first
end

#pick_valueObject

Return a random value of self.

{:one => 1, :two => 2, :three => 3}.pick_value  #=> 3


140
141
142
# File 'lib/rand.rb', line 140

def pick_value
  values.pick
end

#pick_value!Object

Delete a random key-value pair of self and return the value.

a = {:one => 1, :two => 2, :three => 3}
a.pick_value!  #=> 2
a       #=> {:one => 1, :three => 3}


156
157
158
# File 'lib/rand.rb', line 156

def pick_value!
  pick!.last
end

#shuffle_hashObject

Return a copy of self with values arranged in random order.

{:one => 1, :two => 2, :three => 3}.shuffle_hash
   #=> {:two=>2, :three=>1, :one=>3}


171
172
173
174
175
176
177
# File 'lib/rand.rb', line 171

def shuffle_hash
  shuffled = {}
  shuffle_hash_pairs.each{|k, v|
    shuffled[k] = v
  }
  shuffled
end

#shuffle_hash!Object

Destructive shuffle_hash. Arrange the values of self in new, random order.

h = {:one => 1, :two => 2, :three => 3}
h.shuffle_hash!
h  #=> {:two=>2, :three=>1, :one=>3}


184
185
186
187
188
189
# File 'lib/rand.rb', line 184

def shuffle_hash!
  shuffle_hash_pairs.each{|k, v|
    self[k] = v
  }
  self
end

#shuffle_hash_pairsObject

Return the key-value pairs of self with keys and values shuffled independedly.

{:one => 1, :two => 2, :three => 3}.shuffle_hash_pairs
   #=> [[:one, 3], [:two, 1], [:three, 2]]


164
165
166
# File 'lib/rand.rb', line 164

def shuffle_hash_pairs
  keys.shuffle.zip(values.shuffle)
end