How to change Hash values?

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

    Since ruby 2.4.0 you can use native Hash#transform_values method:

    hash = {"a" => "b", "c" => "d"}
    new_hash = hash.transform_values(&:upcase)
    # => {"a" => "B", "c" => "D"}
    

    There is also destructive Hash#transform_values! version.

    0 讨论(0)
  • 2020-12-12 12:03

    Try this function:

    h = {"a" => "b", "c" => "d"}
    h.each{|i,j| j.upcase!} # now contains {"a" => "B", "c" => "D"}.
    
    0 讨论(0)
  • 2020-12-12 12:03

    Ruby has the tap method (1.8.7, 1.9.3 and 2.1.0) that's very useful for stuff like this.

    original_hash = { :a => 'a', :b => 'b' }
    original_hash.clone.tap{ |h| h.each{ |k,v| h[k] = v.upcase } }
    # => {:a=>"A", :b=>"B"}
    original_hash # => {:a=>"a", :b=>"b"}
    
    0 讨论(0)
  • 2020-12-12 12:05

    If you know that the values are strings, you can call the replace method on them while in the cycle: this way you will change the value.

    Altohugh this is limited to the case in which the values are strings and hence doesn't answer the question fully, I thought it can be useful to someone.

    0 讨论(0)
  • 2020-12-12 12:07

    I do something like this:

    new_hash = Hash[*original_hash.collect{|key,value| [key,value + 1]}.flatten]

    This provides you with the facilities to transform the key or value via any expression also (and it's non-destructive, of course).

    0 讨论(0)
  • 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!.

    0 讨论(0)
提交回复
热议问题