class Hash

Public Instance Methods

at(what) → aHash click to toggle source

Returns the key/value pair of hash at key position what. Remember that hashes might not have the intended (or expected) order in pre-1.9 Ruby.

   # File lib/nuggets/hash/at.rb
36 def at(what, &block)
37   return {} if empty?
38 
39   key = what.is_a?(::Integer) ? keys[what] : keys.send(*what, &block)
40 
41   { key => self[key] }
42 end
first → aHash click to toggle source

Returns the “first” key/value pair of hash.

   # File lib/nuggets/hash/at.rb
48 def first
49   at(:first)
50 end
in_order(*ordered) → anArray click to toggle source

Returns hash#to_a, in forced order (cf. Array#in_order).

Examples:

{ a: 1, b: 2, c: 3 }.in_order(:b, :c)  #=> [[:b, 2], [:c, 3], [:a, 1]]
{ a: 1, b: 2, c: 3 }.in_order(:b, :d)  #=> [[:b, 2], [:a, 1], [:c, 3]]
   # File lib/nuggets/hash/in_order.rb
39 def in_order(*ordered)
40   keys.in_order(*ordered).map { |key| [key, self[key]] }
41 end
insert(other) → new_hash click to toggle source
insert(other) { |key, old_value, new_value| ... } → new_hash

Inserts other into hash, while merging existing values instead of just overwriting. Uses default Hash#merge or block for merging.

   # File lib/nuggets/hash/insert.rb
35 def insert(other, &block)
36   block ||= lambda { |key, old_val, new_val|
37     old_val.is_a?(::Hash) && new_val.is_a?(::Hash) ?
38       old_val.merge(new_val, &block) : new_val
39   }
40 
41   merge(other, &block)
42 end
insert!(other) → hash click to toggle source
insert!(other) { |key, old_value, new_value| ... } → hash

Destructive version of insert.

   # File lib/nuggets/hash/insert.rb
49 def insert!(other, &block)
50   replace(insert(other, &block))
51 end
last → aHash click to toggle source

Returns the “last” key/value pair of hash.

   # File lib/nuggets/hash/at.rb
56 def last
57   at(:last)
58 end
only → aHash click to toggle source
only(+true+) → aHash

Returns the only key/value pair of hash. Raises an IndexError if hash's size is not 1, unless parameter true is passed.

   # File lib/nuggets/hash/only.rb
37 def only(relax = size == 1, split = false)
38   relax ? split ? Array(*first) : first :
39     raise(::IndexError, 'not a single-element hash')
40 end
only_pair → anArray click to toggle source
only_pair(+true+) → anArray

Returns the only key/value pair of hash as an array. Raises an IndexError if hash's size is not 1, unless parameter true is passed.

   # File lib/nuggets/hash/only.rb
48 def only_pair(relax = size == 1)
49   only(relax, true)
50 end
rand → aHash click to toggle source

Returns a random key/value pair of hash.

   # File lib/nuggets/hash/at.rb
64 def rand
65   at(:rand)
66 end