I use this code to merge a Matchdata with a Hash :
params = {
:url => 'http://myradiowebsite.com/thestation'
}
pattern = Regexp.new('^https?://(?:www.)?myradiowebsite.com/(?<station_slug>[^/]+)/?$')
matchdatas = pattern.match(params[:url])
#convert named matches in MatchData to Hash
#https://stackoverflow.com/a/11690565/782013
datas = Hash[ matchdatas.names.zip( matchdatas.captures ) ]
params = params.merge(datas)
But this gives me mixed keys in my params hash:
{:url=>"http://myradiowebsite.com/thestation", "station_slug"=>"thestation"}
Which is a problem to get the hash values using the keys later. I would like to standardize them to symbols.
I'm learning Ruby, can someone explain me if there is something wrong with this code, and how to improve it ?
Thanks !
You could transform the keys of datas
to symbols:
Hash[ matchdatas.names.zip( matchdatas.captures ) ].transform_keys(&:to_sym)
Or to define your params hash with string keys:
params = { 'url' => 'http://myradiowebsite.com/thestation' }