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, line 36
def at(what, &block)
  return {} if empty?

  key = what.is_a?(::Integer) ? keys[what] : keys.send(*what, &block)

  { key => self[key] }
end
first → aHash click to toggle source

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

# File lib/nuggets/hash/at.rb, line 48
def first
  at(:first)
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, line 39
def in_order(*ordered)
  keys.in_order(*ordered).map { |key| [key, self[key]] }
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, line 35
def insert(other, &block)
  block ||= lambda { |key, old_val, new_val|
    old_val.is_a?(::Hash) && new_val.is_a?(::Hash) ?
      old_val.merge(new_val, &block) : new_val
  }

  merge(other, &block)
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, line 49
def insert!(other, &block)
  replace(insert(other, &block))
end
last → aHash click to toggle source

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

# File lib/nuggets/hash/at.rb, line 56
def last
  at(:last)
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, line 37
def only(relax = size == 1, split = false)
  relax ? split ? Array(*first) : first :
    raise(::IndexError, 'not a single-element hash')
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, line 48
def only_pair(relax = size == 1)
  only(relax, true)
end
rand → aHash click to toggle source

Returns a random key/value pair of hash.

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