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]


91
92
93
94
# File 'lib/rand.rb', line 91

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}


100
101
102
103
104
# File 'lib/rand.rb', line 100

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


108
109
110
# File 'lib/rand.rb', line 108

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}


122
123
124
# File 'lib/rand.rb', line 122

def pick_key!
  pick!.first
end

#pick_valueObject

Return a random value of self.

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


114
115
116
# File 'lib/rand.rb', line 114

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}


130
131
132
# File 'lib/rand.rb', line 130

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}


145
146
147
148
149
150
151
# File 'lib/rand.rb', line 145

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}


158
159
160
161
162
163
# File 'lib/rand.rb', line 158

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]]


138
139
140
# File 'lib/rand.rb', line 138

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