Forum: Ruby Problem constructing a url with uri

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Peter H. (Guest)
on 2006-06-08 15:34
(Received via mailing list)
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?
Logan C. (Guest)
on 2006-06-08 18:24
(Received via mailing list)
On Jun 8, 2006, at 7:34 AM, Peter H. wrote:

>
>        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
#=> "http://ruby-lang.org?ruby"
Chris (Guest)
on 2006-06-08 18:36
From looking at the code, it seems to expect the query to be a string in
the appropriate format.

Cheers
Daniel S. (Guest)
on 2006-06-08 18:57
(Received via mailing list)
Peter H. 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
This topic is locked and can not be replied to.