Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a %20 with a space in Ruby

I've currently got a string that reads something like ["green%20books"] and I'd like it to read ["green books"].

I thought Googling for this would yield a result pretty quickly but everyone just wants to turn spaces into %20s. Not the other way around.

Any help would be much appreciated!

Edit:

This is the function I'm working with and I'm confused where in here to decode the URL. I tried removing the URI.encode text but that broke the function.

def self.get_search_terms(search_url)
    hash = CGI.parse(URI.parse(URI.encode(search_url)).query) #returns a hash
    keywords = []
    hash.each do |key, value|
      if key == "q" || key == "p"
        keywords << value
      end
    end
    keywords
  end
like image 954
Zack Shapiro Avatar asked Nov 28 '22 11:11

Zack Shapiro


1 Answers

you can use the 'unencode' method of URI. (aliased as decode)

require 'uri'
URI.decode("green%20books")
# => "green books"

this will not only replaces "%20" with space, but every uri-encoded charcter, which I assume is what you want.

documentation

like image 127
YenTheFirst Avatar answered Dec 19 '22 11:12

YenTheFirst