How to change Hash values?

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

    You can collect the values, and convert it from Array to Hash again.

    Like this:

    config = Hash[ config.collect {|k,v| [k, v.upcase] } ]
    
    0 讨论(0)
  • 2020-12-12 12:15

    This will do it:

    my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }
    

    As opposed to inject the advantage is that you are in no need to return the hash again inside the block.

    0 讨论(0)
  • 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=>#<BigDecimal:5c03a00,'0.234E2',18(18)>}
    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

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

    You may want to go a step further and do this on a nested hash. Certainly this happens a fair amount with Rails projects.

    Here's some code to ensure a params hash is in UTF-8:

      def convert_hash hash
        hash.inject({}) do |h,(k,v)|
          if v.kind_of? String
            h[k] = to_utf8(v) 
          else
            h[k] = convert_hash(v)
          end
          h
        end      
      end    
    
      # Iconv UTF-8 helper
      # Converts strings into valid UTF-8
      #
      # @param [String] untrusted_string the string to convert to UTF-8
      # @return [String] your string in UTF-8
      def to_utf8 untrusted_string=""
        ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
        ic.iconv(untrusted_string + ' ')[0..-2]
      end  
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 12:21
    new_hash = old_hash.merge(old_hash) do |_key, value, _value|
                 value.upcase
               end
    
    # old_hash = {"a" => "b", "c" => "d"}
    # new_hash = {"a" => "B", "c" => "D"}
    
    0 讨论(0)
提交回复
热议问题