How to change Hash values?

后端 未结 12 1920
悲&欢浪女
悲&欢浪女 2020-12-12 11:22

I\'d like to replace each value in a hash with value.some_method.

For example, for given a simple hash:

{\"a\" => \"b\",         


        
12条回答
  •  旧巷少年郎
    2020-12-12 12:19

    my_hash.each { |k, v| my_hash[k] = v.upcase } 
    

    or, if you'd prefer to do it non-destructively, and return a new hash instead of modifying my_hash:

    a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h } 
    

    This last version has the added benefit that you could transform the keys too.

提交回复
热议问题