Problem constructing a url with uri

I have this, example, code:

require 'uri'

a = Hash.new
a["fred"] = 42
a["tom"] = "dick"

x = URI::HTTP.build( {:host => "fred.com", :query => a} )
puts x.to_s

Which I was expecting to create a url like http://fred.com/?fred=42&tom=dick but all I get is

/usr/lib/ruby/1.8/uri/generic.rb:508:in `=~': can't convert Hash into String (TypeError)
        from /usr/lib/ruby/1.8/uri/generic.rb:508:in `check_query'
        from /usr/lib/ruby/1.8/uri/generic.rb:523:in `query='
        from /usr/lib/ruby/1.8/uri/generic.rb:178:in `initialize'
        from /usr/lib/ruby/1.8/uri/http.rb:46:in `initialize'
        from /usr/lib/ruby/1.8/uri/generic.rb:125:in `new'
        from /usr/lib/ruby/1.8/uri/generic.rb:125:in `build'
        from /usr/lib/ruby/1.8/uri/http.rb:36:in `build'
        from x:7

Am I correct in my assumption that :query will take a hash and the correct arguments or do I need to create my own function to do the conversion?

:query appears to have be a string. All it does afaict is tack a ? with the string for query on the end.

e.g.

URI::HTTP.build(:host => "ruby-lang.org", :query => "ruby").to_s
#=> "Ruby Programming Language;

···

On Jun 8, 2006, at 7:34 AM, Peter Hickman wrote:

I have this, example, code:

require 'uri'

a = Hash.new
a["fred"] = 42
a["tom"] = "dick"

x = URI::HTTP.build( {:host => "fred.com", :query => a} )
puts x.to_s

Which I was expecting to create a url like http://fred.com/?fred=42&tom=dick but all I get is

/usr/lib/ruby/1.8/uri/generic.rb:508:in `=~': can't convert Hash into String (TypeError)
       from /usr/lib/ruby/1.8/uri/generic.rb:508:in `check_query'
       from /usr/lib/ruby/1.8/uri/generic.rb:523:in `query='
       from /usr/lib/ruby/1.8/uri/generic.rb:178:in `initialize'
       from /usr/lib/ruby/1.8/uri/http.rb:46:in `initialize'
       from /usr/lib/ruby/1.8/uri/generic.rb:125:in `new'
       from /usr/lib/ruby/1.8/uri/generic.rb:125:in `build'
       from /usr/lib/ruby/1.8/uri/http.rb:36:in `build'
       from x:7

Am I correct in my assumption that :query will take a hash and the correct arguments or do I need to create my own function to do the conversion?

From looking at the code, it seems to expect the query to be a string in
the appropriate format.

Cheers

···

--
Posted via http://www.ruby-forum.com/.

Peter Hickman wrote:

a = Hash.new
a["fred"] = 42
a["tom"] = "dick"

x = URI::HTTP.build( {:host => "fred.com", :query => a} )

:query should be a string -- or rather, should respond to #to_str.

   q = {:fred => 42, :tom => 'dick'}
   def q.to_str
     collect{|name, value| "#{name}=#{value}"}.join('&')
   end
   uri = URI::HTTP.build(:host => "fred.com", :query => q)

Cheers,
Daniel