温馨提示:本文翻译自stackoverflow.com,查看原文请点击:regex - make hash consistent when some of its keys are symbols and others are not
hash regex ruby

regex - 当哈希的某些键是符号而其他键不是符号时,使哈希保持一致

发布于 2020-03-30 21:29:52

我使用以下代码将Matchdata与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)

但这给我的参数哈希中的混合键

{:url =>“ http://myradiowebsite.com/thestation ”,“ station_slug” =>“ thestation”}

稍后使用键获取哈希值是一个问题。我想将它们标准化为符号。

我正在学习Ruby,如果该代码有问题,有人可以向我解释,以及如何对其进行改进?

谢谢 !

查看更多

提问者
gordie
被浏览
99
Sebastian Palma 2020-01-31 15:48

您可以将的键转换datas为符号:

Hash[ matchdatas.names.zip( matchdatas.captures ) ].transform_keys(&:to_sym)

或使用字符串键定义参数哈希:

params = { 'url' => 'http://myradiowebsite.com/thestation' }