【问题标题】:make hash consistent when some of its keys are symbols and others are not当一些键是符号而其他键不是时,使哈希保持一致
【发布时间】:2020-05-16 21:04:01
【问题描述】:

我使用此代码将 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)

但这在我的 params 哈希中提供了混合键:

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

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

我正在学习 Ruby,如果这段代码有问题,谁能解释我,以及如何改进它?

谢谢!

【问题讨论】:

  • 您可以跳过转换并注入您需要的密钥params[:station_slug] = matchdatas[:station_slug]。为什么你甚至需要这个?你可以试试URI.parse分解网址。

标签: regex ruby hash


【解决方案1】:

首先,注意与

pattern = 
  Regexp.new('^https?://(?:www.)?myradiowebsite.com/(?<station_slug>[^/]+)/?$')
  #=> /^https?:\/\/(?:www.)?myradiowebsite.com\/(?<station_slug>[^\/]+)\/?$/ 

我们得到

'http://wwwXmyradiowebsiteYcom/thestation'.match?(pattern)
   #=> true

这意味着'www'之后和'com'之前的句点需要转义:

pattern =
  Regexp.new('\Ahttps?://(?:www\.)?myradiowebsite\.com/(?<station_slug>[^/]+)/?\z')
  #=> /\Ahttps?:\/\/(?:www\.)?myradiowebsite\.com\/(?<station_slug>[^\/]+)\/?\z/ 

我还将行首锚 (^) 替换为字符串开头锚 (\A),并将行尾锚 ($) 替换为 end-字符串锚点 (\z),但可以在此处使用任何一个,因为字符串由单行组成。

在返回的哈希中为您提供了两个键::url 和 :station_slug,所以对于

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

你可以计算

m = params[:url].match(pattern)
  #=> #<MatchData "http://myradiowebsite.com/thestation" station_slug:"thestation"> 

那么只要m 不是nil(如这里),就写

{ :url => m[0], :station_slug => m["station_slug"] }
  #=> {:url=>"http://myradiowebsite.com/thestation", :station_slug=>"thestation"}

见MatchData#[]。 m[0] 返回整个匹配; m["station_slug"] 返回名为 "station_slug" 的捕获组的内容。

显然,捕获组的名称可以是任何有效的字符串,或者您可以将其设为未命名的捕获组并写入

{ :url => m[0], :station_slug => m[1] }

【讨论】:

    【解决方案2】:

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

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

    或者用字符串键定义你的参数哈希:

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

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 2015-11-23
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多