How to change Hash values?

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

提交回复
热议问题