Hi *, my question is really simple: is there a way in Ruby stdlib or in
external modules to build querystrings without creating the string from
scratch ?
For example something like:
name = “Foo B.”
p URI::join(base_uri, query_string(name))
Obviously this code is totally invented.
If not (haven’t found anything in the documentation) how does people
accomplish this task ?
TIA,
ngw
harp:~ > cat a.rb
require “cgi”
class Hash
def query_string
“?” << inject([]){|a,kv| a << [CGI.escape(kv.shift),
CGI.escape(kv.shift)].join(“=”) }.join(“&”)
end
end
Wow, I have no idea what this does or how it works. Would you mind
taking this apart and describing how it works?
“?”<<map{|h|h.map{|e|CGI.escape(e)}‘=’}‘&’
This can be spaced out a bit:
“?” << # append what follows to the string ‘?’
map { |h| # h looks like [‘key’, ‘value’] for each key-value
pair
h.map { |e| # e looks like ‘key’ or ‘value’
CGI.escape(e) # escape each element
} * ‘=’ # join key and value with ‘=’
} * ‘&’ # join each key-value pair with ‘&’
Is that any clearer?
Paul.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.