【发布时间】: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分解网址。