Class: Hash
Overview
reopening Hash class
Instance Method Summary collapse
-
#reverse_merge(other_hash) ⇒ Hash
Performs a non-destructive reverse merge with another hash This is particularly useful for initializing an options hash with default values.
-
#reverse_merge!(other_hash) ⇒ Hash
(also: #reverse_update)
Performs a destructive reverse merge with another hash.
-
#to_html_attributes(empties = nil) ⇒ String
Converts a hash into HTML attribute string representation.
Instance Method Details
#reverse_merge(other_hash) ⇒ Hash
Performs a non-destructive reverse merge with another hash This is particularly useful for initializing an options hash with default values.
is equivalent to
= { size: 25, velocity: 10 }.merge()
45 46 47 |
# File 'lib/core_ext/hash.rb', line 45 def reverse_merge(other_hash) other_hash.merge(self) end |
#reverse_merge!(other_hash) ⇒ Hash Also known as: reverse_update
Performs a destructive reverse merge with another hash. Modifies the original hash by merging in the provided hash while keeping existing values.
63 64 65 66 |
# File 'lib/core_ext/hash.rb', line 63 def reverse_merge!(other_hash) # right wins if there is no left merge!(other_hash) { |_key, left, _right| left } end |
#to_html_attributes(empties = nil) ⇒ String
Converts a hash into HTML attribute string representation.
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/core_ext/hash.rb', line 18 def to_html_attributes(empties = nil) hash = dup hash.reject! { |_k, v| v.blank? } unless empties.nil? out = '' hash.keys.sort.each do |key| # NB!! sorting output order of attributes alphabetically val = hash[key].is_a?(Array) ? hash[key].join('_') : hash[key].to_s out << "#{key}=\"#{val}\" " end out.strip end |