ruby map_hash_to_hash.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby map_hash_to_hash.rb相关的知识,希望对你有一定的参考价值。

source: http://avdi.org/devblog/2009/11/20/hash-transforms-in-ruby/

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}

以上是关于ruby map_hash_to_hash.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee