Doublespeed Doublespeed - 10 months ago 49
Ruby Question

Not sure what this ruby method does

The below method is some code I inherited and it's supposed to remove parameters from a url but it's breaking with the following error:

ArgumentError: the input of URI.decode_www_form must be ASCII only

def self.removeUnnecessaryGetParams(url, removeParams = ["s"], whiteListParams = nil)
uri = Addressable::URI.parse(url)

#Get rid of UTM parameters & S parameters
if(uri.query != nil)

if(whiteListParams != nil)
cleanKeyVals = URI.decode_www_form(uri.query).reject{|k, _| !whiteListParams.include?(k)}
cleanKeyVals = URI.decode_www_form(uri.query).reject{|k, _| k.start_with?("utm_") or removeParams.include?(k)}

uri.query = URI.encode_www_form(cleanKeyVals)

return uri.to_s.split("#")[0].chomp("?")

1). My Question is, how exactly is this method working? Not sure what the lines are doing that assign to
(my ruby knowledge shortcomings).

2). How to fix this ASCII only string issue?

Answer Source
  1. uri.query appears to be a Ruby Hash object, #reject will reject entries in the object that meet the predicate described within the block. The first sieve removes keys not in the whitelist, the second rejects based on keys that start with utm_ or keys that are within removeParams.
  2. Simply do url.gsub!(/\P{ASCII}/, '') on the line immediately following the function definition. This regex will strip out non ASCII characters for you. (As an aside #gsub! modifies the original while #gsub returns a copy, this is a common Ruby convention that you will see as you start to explore the language more)