Class: Hash
Overview
reopening Hash class
Instance Method Summary collapse
-
#reverse_merge(other_hash) ⇒ Object
Merges the caller into
other_hash
. -
#reverse_merge!(other_hash) ⇒ Object
(also: #reverse_update)
Destructive
reverse_merge
. - #to_html_attributes(empties = nil) ⇒ Object
Instance Method Details
#reverse_merge(other_hash) ⇒ Object
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.
30 31 32 |
# File 'lib/core_ext/hash.rb', line 30 def reverse_merge(other_hash) other_hash.merge(self) end |
#reverse_merge!(other_hash) ⇒ Object Also known as: reverse_update
Destructive reverse_merge
.
38 39 40 41 |
# File 'lib/core_ext/hash.rb', line 38 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) ⇒ Object
7 8 9 10 11 12 13 14 15 16 |
# File 'lib/core_ext/hash.rb', line 7 def to_html_attributes(empties = nil) hash = self.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 |