Hash转换为查询字符串

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#依赖addressable/uri
require 'addressable/uri'

def _to_query_string(hash)
    if hash.instance_of? String
      URI.encode hash
    else
      uri = Addressable::URI.new
      uri.query_values = hash
      uri.query
    end
end

#使用方法:
query_string = _to_query_string( {'name'=>'hello', 'hello'=>'world'} )
puts query_string 
#输出:name=hello&pwd=world
query_string = _to_query_string "name=hello&pwd=world"
puts query_string
#输出:name=hello&pwd=world