Warm tip: This article is reproduced from stackoverflow.com, please click
hash regex ruby

make hash consistent when some of its keys are symbols and others are not

发布于 2020-03-30 21:13:03

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 !

Questioner
gordie
Viewed
69
Sebastian Palma 2020-01-31 15:48

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' }