如何使用 Ruby 中哈希的查询参数构造 URI

How to construct URI with query arguments from hash in Ruby

如何通过传递哈希来构造带有查询参数的 URI 对象?

我可以生成查询:

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

生成

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

但是我认为为许多参数构造查询字符串将不可读且难以维护。我想通过传递哈希来构造查询字符串。就像下面的例子:

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

这提高了

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

是否可以使用 URI api 基于哈希构造查询字符串?我不想猴子修补哈希对象...

如果您有 ActiveSupport,只需在哈希上调用 '#to_query'

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

如果你不使用rails记得require 'uri'

对于那些不使用 Rails 或 Active Support 的人,使用 Ruby 标准库的解决方案是

hash = {
  a: 'argument1',
  b: 'argument2'
}
URI::HTTPS.build(host: 'example.com', query: URI.encode_www_form(hash))
=> #<URI::HTTPS https://example.com?a=argument1&b=argument2>