convert ruby hash to URL query string … without those square brackets

不想你离开。 提交于 2019-12-03 12:32:23
Aaron Jensen

In modern ruby this is simply:

require 'uri'
URI.encode_www_form(hash)

Here's a quick function to turn your hash into query parameters:

require 'uri'
def hash_to_query(hash)
  return URI.encode(hash.map{|k,v| "#{k}=#{v}"}.join("&"))
end

Quick Hash to a URL Query Trick :

"http://www.example.com?" + { language: "ruby", status: "awesome" }.to_query

# => "http://www.example.com?language=ruby&status=awesome"

Want to do it in reverse? Use CGI.parse:

require 'cgi' 
# Only needed for IRB, Rails already has this loaded

CGI::parse "language=ruby&status=awesome"

# => {"language"=>["ruby"], "status"=>["awesome"]} 

The way rails handles query strings of that type means you have to roll your own solution, as you have. It is somewhat unfortunate if you're dealing with non-rails apps, but makes sense if you're passing information to and from rails apps.

As a simple plain Ruby solution (or RubyMotion, in my case), just use this:

class Hash
  def to_param
    self.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
  end
end

{ fruit: "Apple", vegetable: "Carrot" }.to_param # => "fruit=Apple&vegetable=Carrot"

It only handles simple hashes, though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!