3

I want to form a url like

http://www.google.com?name=john%20doe

using Ruby.

I have

u = URI::HTTP.build(host: 'www.google.com', query: { name: 'john doe' }.to_query)

u.to_s gives me http://www.google.com?name=john+doe.

The whitespace in john doe is replaced with + because

{ name: 'john doe' }.to_query

returns name=john+doe (to_query is a Rails addition I believe)

I want %20 instead of +. How do I achieve this easily?

I'm aware that URI::encode does encode a whitespace to a %20, but I wonder if there's a better way than converting a hash to a string and then sending it through URI::encode.

Zack Xu
  • 11,505
  • 9
  • 70
  • 78
  • 1
    Both + and %20 are valid in the query string portion as spaces, so what is being generated is correct according to the RFC. See: https://stackoverflow.com/a/2678602 – Joe May 11 '18 at 13:27

1 Answers1

1

Use: url_encode('john doe') Docs

DonPaulie
  • 2,004
  • 17
  • 26