如何通过传递哈希来构造带有查询参数的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基于哈希构造查询字符串?我不想对哈希对象进行猴子补丁操作...
to_query
是 Rails 中的一个方法,在 Ruby 中并不存在。 - marc_ferna