Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#assert_valid_keys(*valid_keys) ⇒ Object

Validate all keys in a hash match *valid keys, raising ArgumentError on a mismatch. Note that keys are NOT treated indifferently, meaning if you use strings for keys but assert symbols as keys, this will fail.

Examples

{ :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key(s): years"
{ :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key(s): name, age"
{ :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing

Raises:

  • (ArgumentError)


46
47
48
49
# File 'lib/ext.rb', line 46

def assert_valid_keys(*valid_keys)
  unknown_keys = keys - [valid_keys].flatten
  raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end

#require_keys(*required_keys) ⇒ Object



51
52
53
54
55
56
# File 'lib/ext.rb', line 51

def require_keys(*required_keys)
  missing_keys = [required_keys].flatten - keys
  if missing_keys.size>0
    raise(ArgumentError, "Missing key(s): #{missing_keys.join(', ')}")
  end
end

#reverse_merge(other_hash) ⇒ Object



3
4
5
# File 'lib/ext.rb', line 3

def reverse_merge(other_hash)
  other_hash.merge(self)
end

#stringify_keysObject

Return a new hash with all keys converted to strings.



8
9
10
# File 'lib/ext.rb', line 8

def stringify_keys
  dup.stringify_keys!
end

#stringify_keys!Object

Destructively convert all keys to strings.



13
14
15
16
17
18
# File 'lib/ext.rb', line 13

def stringify_keys!
  keys.each do |key|
    self[key.to_s] = delete(key)
  end
  self
end

#symbolize_keysObject Also known as: to_options

Return a new hash with all keys converted to symbols, as long as they respond to to_sym.



22
23
24
# File 'lib/ext.rb', line 22

def symbolize_keys
  dup.symbolize_keys!
end

#symbolize_keys!Object Also known as: to_options!

Destructively convert all keys to symbols, as long as they respond to to_sym.



28
29
30
31
32
33
# File 'lib/ext.rb', line 28

def symbolize_keys!
  keys.each do |key|
    self[(key.to_sym rescue key)] = delete(key) if key.respond_to?(:to_sym) && !key.is_a?(Fixnum)
  end
  self
end