avdi (owner)

Revisions

gist: 239563 Download_button fork
public
Public Clone URL: git://gist.github.com/239563.git
Embed All Files: show embed
map_hash_to_hash.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def map_hash_to_hash(original, options={})
  original.inject({}){|a, (key,value)|
    catch(:skip) do
      value = if (options[:deep] && Hash === value)
                map_hash_to_hash(value) {|k,v| yield(k, v) }
              else
                value
              end
      new_key, new_value = yield(key,value)
      a[new_key] = new_value
    end
    a
  }
end
 
h = { :foo => 1, :bar => {:baz => 3}, :buz => 4 }
 
h.map{|k,v| [k.to_s, v]} # => [["buz", 4], ["foo", 1], ["bar", {:baz=>3}]]
 
# Convert keys to strings
def stringify_keys(hash)
  map_hash_to_hash(hash) {|key, value|
    [key.to_s, value]
  }
end
stringify_keys(h) # => {"foo"=>1, "buz"=>4, "bar"=>{:baz=>3}}
 
# Convert keys to strings, recursively
def deep_stringify_keys(hash)
  map_hash_to_hash(hash, :deep => true) {|key, value|
    [key.to_s, value]
  }
end
deep_stringify_keys(h) # => {"foo"=>1, "buz"=>4, "bar"=>{"baz"=>3}}
 
# Select a subset of entries
def slice_hash(hash, *keys)
  map_hash_to_hash(hash, :deep => true) {|key, value|
    throw :skip unless keys.include?(key)
    [key, value]
  }
end
slice_hash(h, :foo, :buz) # => {:buz=>4, :foo=>1}