avdi (owner)

Forks

Revisions

gist: 239567 Download_button fork
public
Public Clone URL: git://gist.github.com/239567.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
def transform_hash(original, options={}, &block)
  original.inject({}){|result, (key,value)|
    value = if (options[:deep] && Hash === value)
              transform_hash(value, options, &block)
            else
              value
            end
    block.call(result,key,value)
    result
  }
end
 
h = { :foo => 1, :bar => {:baz => 3}, :buz => 4 }
 
h.map{|k,v| [k.to_s, v]} # => [["foo", 1], ["bar", {:baz=>3}], ["buz", 4]]
 
# Convert keys to strings
def stringify_keys(hash)
  transform_hash(hash) {|hash, key, value|
    hash[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)
  transform_hash(hash, :deep => true) {|hash, key, value|
    hash[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)
  transform_hash(hash, :deep => true) {|hash, key, value|
    hash[key] = value if keys.include?(key)
  }
end
slice_hash(h, :foo, :buz) # => {:foo=>1, :buz=>4}