Class: Hash
- Defined in:
- lib/simple_ext/hash/keys.rb,
lib/simple_ext/hash/check.rb,
lib/simple_ext/hash/merge.rb,
lib/simple_ext/hash/slice.rb,
lib/simple_ext/hash/except.rb,
lib/simple_ext/hash/values.rb,
lib/simple_ext/object/blank.rb,
lib/simple_ext/object/to_query.rb
Instance Method Summary collapse
-
#assert_valid_keys(*valid_keys) ⇒ Object
Validates all keys in a hash match
*valid_keys
, raisingArgumentError
on a mismatch. -
#deep_merge(other_hash, &block) ⇒ Object
Returns a new hash with
self
andother_hash
merged recursively. -
#deep_merge!(other_hash, &block) ⇒ Object
Same as
deep_merge
, but modifiesself
. -
#deep_stringify_keys ⇒ Object
Returns a new hash with all keys converted to strings.
-
#deep_stringify_keys! ⇒ Object
Destructively converts all keys to strings.
-
#deep_symbolize_keys ⇒ Object
Returns a new hash with all keys converted to symbols, as long as they respond to
to_sym
. -
#deep_symbolize_keys! ⇒ Object
Destructively converts all keys to symbols, as long as they respond to
to_sym
. -
#deep_transform_keys(&block) ⇒ Object
Returns a new hash with all keys converted by the block operation.
-
#deep_transform_keys!(&block) ⇒ Object
Destructively converts all keys by using the block operation.
-
#deep_transform_values(&block) ⇒ Object
Returns a new hash with all values converted by the block operation.
-
#deep_transform_values!(&block) ⇒ Object
Destructively converts all values by using the block operation.
-
#except(*keys) ⇒ Object
Returns a hash that includes everything except given keys.
-
#except!(*keys) ⇒ Object
Removes the given keys from hash and returns it.
-
#extract!(*keys) ⇒ Object
Removes and returns the key/value pairs matching the given keys.
-
#reverse_merge(other_hash) ⇒ Object
(also: #with_defaults)
Merges the caller into
other_hash
. -
#reverse_merge!(other_hash) ⇒ Object
(also: #reverse_update, #with_defaults!)
Destructive
reverse_merge
. -
#slice!(*keys) ⇒ Object
Replaces the hash with only the given keys.
-
#stringify_keys ⇒ Object
Returns a new hash with all keys converted to strings.
-
#stringify_keys! ⇒ Object
Destructively converts all keys to strings.
-
#sub_hash?(hash) ⇒ Boolean
Check if given hash is sub hash of current hash 1, b: 2, c: 3, d: 4.sub_hash?(1, b: 2) => true 1, b: 2, c: 3, d: 4.sub_hash?(1, b: 2) => false.
-
#sub_hash_of?(hash) ⇒ Boolean
Check if current hash is sub hash of given hash 1, b: 2.sub_hash_of?(1, b: 2, c: 3, d: 4) => true 1, b: 2.sub_hash_of?(1, b: 5, c: 3, d: 4) => false.
-
#symbolize_keys ⇒ Object
(also: #to_options)
Returns a new hash with all keys converted to symbols, as long as they respond to
to_sym
. -
#symbolize_keys! ⇒ Object
(also: #to_options!)
Destructively converts all keys to symbols, as long as they respond to
to_sym
. -
#to_query(namespace = nil) ⇒ Object
(also: #to_param)
Returns a string representation of the receiver suitable for use as a URL query string:.
Instance Method Details
#assert_valid_keys(*valid_keys) ⇒ Object
Validates all keys in a hash match *valid_keys
, raising ArgumentError
on a mismatch.
Note that keys are treated differently than HashWithIndifferentAccess, meaning that string and symbol keys will not match.
{ name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
{ name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
{ name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
48 49 50 51 52 53 54 55 |
# File 'lib/simple_ext/hash/keys.rb', line 48 def assert_valid_keys(*valid_keys) valid_keys.flatten! each_key do |k| unless valid_keys.include?(k) raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}") end end end |
#deep_merge(other_hash, &block) ⇒ Object
Returns a new hash with self
and other_hash
merged recursively.
h1 = { a: true, b: { c: [1, 2, 3] } }
h2 = { a: false, b: { x: [3, 4, 5] } }
h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }
Like with Hash#merge in the standard library, a block can be provided to merge values:
h1 = { a: 100, b: 200, c: { c1: 100 } }
h2 = { b: 250, c: { c1: 200 } }
h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
# => { a: 100, b: 450, c: { c1: 300 } }
18 19 20 |
# File 'lib/simple_ext/hash/merge.rb', line 18 def deep_merge(other_hash, &block) dup.deep_merge!(other_hash, &block) end |
#deep_merge!(other_hash, &block) ⇒ Object
Same as deep_merge
, but modifies self
.
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/simple_ext/hash/merge.rb', line 23 def deep_merge!(other_hash, &block) merge!(other_hash) do |key, this_val, other_val| if this_val.is_a?(Hash) && other_val.is_a?(Hash) this_val.deep_merge(other_val, &block) elsif block_given? block.call(key, this_val, other_val) else other_val end end end |
#deep_stringify_keys ⇒ Object
Returns a new hash with all keys converted to strings. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_stringify_keys
# => {"person"=>{"name"=>"Rob", "age"=>"28"}}
84 85 86 |
# File 'lib/simple_ext/hash/keys.rb', line 84 def deep_stringify_keys deep_transform_keys(&:to_s) end |
#deep_stringify_keys! ⇒ Object
Destructively converts all keys to strings. This includes the keys from the root hash and from all nested hashes and arrays.
91 92 93 |
# File 'lib/simple_ext/hash/keys.rb', line 91 def deep_stringify_keys! deep_transform_keys!(&:to_s) end |
#deep_symbolize_keys ⇒ Object
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
hash.deep_symbolize_keys
# => {:person=>{:name=>"Rob", :age=>"28"}}
103 104 105 |
# File 'lib/simple_ext/hash/keys.rb', line 103 def deep_symbolize_keys deep_transform_keys { |key| key.to_sym rescue key } end |
#deep_symbolize_keys! ⇒ Object
Destructively converts all keys to symbols, as long as they respond to to_sym
. This includes the keys from the root hash and from all nested hashes and arrays.
110 111 112 |
# File 'lib/simple_ext/hash/keys.rb', line 110 def deep_symbolize_keys! deep_transform_keys! { |key| key.to_sym rescue key } end |
#deep_transform_keys(&block) ⇒ Object
Returns a new hash with all keys converted by the block operation. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_transform_keys{ |key| key.to_s.upcase }
# => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
65 66 67 |
# File 'lib/simple_ext/hash/keys.rb', line 65 def deep_transform_keys(&block) _deep_transform_keys_in_object(self, &block) end |
#deep_transform_keys!(&block) ⇒ Object
Destructively converts all keys by using the block operation. This includes the keys from the root hash and from all nested hashes and arrays.
72 73 74 |
# File 'lib/simple_ext/hash/keys.rb', line 72 def deep_transform_keys!(&block) _deep_transform_keys_in_object!(self, &block) end |
#deep_transform_values(&block) ⇒ Object
Returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_transform_values{ |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}
12 13 14 |
# File 'lib/simple_ext/hash/values.rb', line 12 def deep_transform_values(&block) _deep_transform_values_in_object(self, &block) end |
#deep_transform_values!(&block) ⇒ Object
Destructively converts all values by using the block operation. This includes the values from the root hash and from all nested hashes and arrays.
19 20 21 |
# File 'lib/simple_ext/hash/values.rb', line 19 def deep_transform_values!(&block) _deep_transform_values_in_object!(self, &block) end |
#except(*keys) ⇒ Object
Returns a hash that includes everything except given keys.
hash = { a: true, b: false, c: nil }
hash.except(:c) # => { a: true, b: false }
hash.except(:a, :b) # => { c: nil }
hash # => { a: true, b: false, c: nil }
This is useful for limiting a set of parameters to everything but a few known toggles:
@person.update(params[:person].except(:admin))
12 13 14 |
# File 'lib/simple_ext/hash/except.rb', line 12 def except(*keys) slice(*self.keys - keys) end |
#except!(*keys) ⇒ Object
Removes the given keys from hash and returns it.
hash = { a: true, b: false, c: nil }
hash.except!(:c) # => { a: true, b: false }
hash # => { a: true, b: false }
20 21 22 23 |
# File 'lib/simple_ext/hash/except.rb', line 20 def except!(*keys) keys.each { |key| delete(key) } self end |
#extract!(*keys) ⇒ Object
Removes and returns the key/value pairs matching the given keys.
{ a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
{ a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
23 24 25 |
# File 'lib/simple_ext/hash/slice.rb', line 23 def extract!(*keys) keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) } end |
#reverse_merge(other_hash) ⇒ Object Also known as: with_defaults
Merges the caller into other_hash
. For example,
= .reverse_merge(size: 25, velocity: 10)
is equivalent to
= { size: 25, velocity: 10 }.merge()
This is particularly useful for initializing an options hash with default values.
45 46 47 |
# File 'lib/simple_ext/hash/merge.rb', line 45 def reverse_merge(other_hash) other_hash.merge(self) end |
#reverse_merge!(other_hash) ⇒ Object Also known as: reverse_update, with_defaults!
Destructive reverse_merge
.
51 52 53 |
# File 'lib/simple_ext/hash/merge.rb', line 51 def reverse_merge!(other_hash) replace(reverse_merge(other_hash)) end |
#slice!(*keys) ⇒ Object
Replaces the hash with only the given keys. Returns a hash containing the removed key/value pairs.
hash = { a: 1, b: 2, c: 3, d: 4 }
hash.slice!(:a, :b) # => {:c=>3, :d=>4}
hash # => {:a=>1, :b=>2}
10 11 12 13 14 15 16 17 |
# File 'lib/simple_ext/hash/slice.rb', line 10 def slice!(*keys) omit = slice(*self.keys - keys) hash = slice(*keys) hash.default = default hash.default_proc = default_proc if default_proc replace(hash) omit end |
#stringify_keys ⇒ Object
Returns a new hash with all keys converted to strings.
hash = { name: 'Rob', age: '28' }
hash.stringify_keys
# => {"name"=>"Rob", "age"=>"28"}
10 11 12 |
# File 'lib/simple_ext/hash/keys.rb', line 10 def stringify_keys transform_keys(&:to_s) end |
#stringify_keys! ⇒ Object
Destructively converts all keys to strings. Same as stringify_keys
, but modifies self
.
16 17 18 |
# File 'lib/simple_ext/hash/keys.rb', line 16 def stringify_keys! transform_keys!(&:to_s) end |
#sub_hash?(hash) ⇒ Boolean
Check if given hash is sub hash of current hash 1, b: 2, c: 3, d: 4.sub_hash?(1, b: 2) => true 1, b: 2, c: 3, d: 4.sub_hash?(1, b: 2) => false
18 19 20 |
# File 'lib/simple_ext/hash/check.rb', line 18 def sub_hash?(hash) merge(hash) == self end |
#sub_hash_of?(hash) ⇒ Boolean
Check if current hash is sub hash of given hash 1, b: 2.sub_hash_of?(1, b: 2, c: 3, d: 4) => true 1, b: 2.sub_hash_of?(1, b: 5, c: 3, d: 4) => false
10 11 12 |
# File 'lib/simple_ext/hash/check.rb', line 10 def sub_hash_of?(hash) hash.merge(self) == hash end |
#symbolize_keys ⇒ Object Also known as: to_options
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
.
hash = { 'name' => 'Rob', 'age' => '28' }
hash.symbolize_keys
# => {:name=>"Rob", :age=>"28"}
27 28 29 |
# File 'lib/simple_ext/hash/keys.rb', line 27 def symbolize_keys transform_keys { |key| key.to_sym rescue key } end |
#symbolize_keys! ⇒ Object Also known as: to_options!
Destructively converts all keys to symbols, as long as they respond to to_sym
. Same as symbolize_keys
, but modifies self
.
34 35 36 |
# File 'lib/simple_ext/hash/keys.rb', line 34 def symbolize_keys! transform_keys! { |key| key.to_sym rescue key } end |
#to_query(namespace = nil) ⇒ Object Also known as: to_param
Returns a string representation of the receiver suitable for use as a URL query string:
{name: 'David', nationality: 'Danish'}.to_query
# => "name=David&nationality=Danish"
An optional namespace can be passed to enclose key names:
{name: 'David', nationality: 'Danish'}.to_query('user')
# => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
The string pairs “key=value” that conform the query string are sorted lexicographically in ascending order.
This method is also aliased as to_param
.
77 78 79 80 81 82 83 84 85 86 |
# File 'lib/simple_ext/object/to_query.rb', line 77 def to_query(namespace = nil) query = collect do |key, value| unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty? value.to_query(namespace ? "#{namespace}[#{key}]" : key) end end.compact query.sort! unless namespace.to_s.include?("[]") query.join("&") end |