How to change Hash values?

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

    There's a method for that in ActiveSupport v4.2.0. It's called transform_values and basically just executes a block for each key-value-pair.

    Since they're doing it with a each I think there's no better way than to loop through.

    hash = {sample: 'gach'}
    
    result = {}
    hash.each do |key, value|
      result[key] = do_stuff(value)
    end
    

    Update:

    Since Ruby 2.4.0 you can natively use #transform_values and #transform_values!.

提交回复
热议问题