Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

How to construct URI object with query arguments by passing hash?

I can generate query with:

URI::HTTPS.build(host: 'example.com', query: "a=#{hash[:a]}, b=#{[hash:b]}")

which generates

https://example.com?a=argument1&b=argument2

however I think constructing query string for many arguments would be unreadable and hard to maintain. I would like to construct query string by passing hash. Like in example below:

hash = {
  a: 'argument1',
  b: 'argument2'
  #... dozen more arguments
}
URI::HTTPS.build(host: 'example.com', query: hash)

which raises

NoMethodError: undefined method `to_str' for {:a=>"argument1", :b=>"argument2"}:Hash

Is it possible to construct query string based on hash using URI api? I don't want to monkey patch hash object...

share|improve this question
up vote 3 down vote accepted

Just call '#to_query' on hash.

hash = {
  a: 'argument1',
  b: 'argument2'
  #... dozen more arguments
}
URI::HTTPS.build(host: 'example.com', query: hash.to_query)

=> https://example.com?a=argument1&b=argument2

If you are not using rails remember to require 'uri'

share|improve this answer
5  
to_query is a Rails only method. It does not exist in Ruby. – marc_ferna Sep 19 '16 at 5:39
1  
@marc_ferna questions has ruby on rails tag. You can include : ActiveSupport in non-rails projects – Filip Bartuzi Sep 30 '16 at 7:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.