Module: HashUtils
- Included in:
- Hash
- Defined in:
- lib/tpkg/metadata.rb
Overview
modules with some handy methods for dealing with hash. taken from ActiveSupport and Facets
Instance Method Summary collapse
- #recursively {|h| ... } ⇒ Object
- #rekey(*args, &block) ⇒ Object
-
#stringify_keys ⇒ Object
Return a new hash with all keys converted to strings.
-
#symbolize_keys ⇒ Object
Return a new hash with all keys converted to symbols.
Instance Method Details
#recursively {|h| ... } ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/tpkg/metadata.rb', line 171 def recursively(&block) h = inject({}) do |hash, (key, value)| if value.is_a?(Hash) hash[key] = value.recursively(&block) elsif value.is_a?(Array) array = [] value.each do |val| if val.is_a?(Hash) array << val.recursively(&block) else array << val end end hash[key] = array else hash[key] = value end hash end yield h end |
#rekey(*args, &block) ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/tpkg/metadata.rb', line 193 def rekey(*args, &block) result = {} # for backward comptability (TODO: DEPRECATE). block = args.pop.to_sym.to_proc if args.size == 1 # if no args use block. if args.empty? block = lambda{|k| k.to_sym} unless block keys.each do |k| nk = block[k] result[nk]=self[k] if nk end else raise ArgumentError, "3 for 2" if block to, from = *args result[to] = self[from] end result end |
#stringify_keys ⇒ Object
Return a new hash with all keys converted to strings.
156 157 158 159 160 161 |
# File 'lib/tpkg/metadata.rb', line 156 def stringify_keys inject({}) do |, (key, value)| [key.to_s] = value end end |
#symbolize_keys ⇒ Object
Return a new hash with all keys converted to symbols.
164 165 166 167 168 169 |
# File 'lib/tpkg/metadata.rb', line 164 def symbolize_keys inject({}) do |, (key, value)| [(key.to_sym rescue key) || key] = value end end |