How to change Hash values?

后端 未结 12 1939
悲&欢浪女
悲&欢浪女 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:15

    Rails-specific

    In case someone only needs to call to_s method to each of the values and is not using Rails 4.2 ( which includes transform_values method link), you can do the following:

    original_hash = { :a => 'a', :b => BigDecimal('23.4') }
    #=> {:a=>"a", :b=>#}
    JSON(original_hash.to_json)
    #=> {"a"=>"a", "b"=>"23.4"}
    

    Note: The use of 'json' library is required.

    Note 2: This will turn keys into strings as well

提交回复
热议问题