Method: Hash#flatten
- Defined in:
- lib/html_attributes/hash.rb
#flatten(sep = $,, prefix_keys = [], &block) ⇒ Object
Returns a new hash flatting the values (recursively), i.e. if a value of self is a hash again 1) the keys are build by combining the key of self (the one to access that hash value) with the keys of that hash; 2) the values are the values of that hash.
You can either specify a seperator to to build the keys joining them, or a block which gets an array of keys and returns the new key.
Examples
styles = { :padding => { :top => "8px", :right => "15px" }, :font_size => "12pt" }
styles.flatten("_")
# => { "padding_top" => "8px", "padding_right" => "15px", "font_size" => "12pt" }
styles.flatten { |keys| keys.join('-').gsub('_', '-') }
# => { "padding-top" => "8px", "padding-right" => "15px", "font-size" => "12pt" }
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/html_attributes/hash.rb', line 76 def flatten(sep = $,, prefix_keys = [], &block) # :nodoc: hash = self.class.new self.each do |key, value| prefix_keys.push(key) case value when ::Hash value.flatten(sep, prefix_keys, &block).each do |k, v| hash[k] = v end else hash[block_given? ? yield(prefix_keys) : prefix_keys.join(sep)] = value end prefix_keys.pop end hash end |