2017-07-13 55 views
0

在哈希,我可以使用我可以为Ruby的MatchData设置默认值吗?

map = Hash.new("(0,0)") 

map = Hash.new() 
map.default = "(0, 0)" 

设置为未定义键的默认值,这样,当我尝试检索未定义键的值,我不会得到一个错误。但在MatchData中,例如:

line = "matchBegins\/blabla\" = (20, 10);" 
get = line.match(/matchBegins\/(?<match1>\D*)" *= *(?<match2>.*);/) 
puts get[:notExisted] 

我会收到一个错误。我检查过MatchData的文档,但不能设置任何设置默认值。我对么?由于

+0

你是指'(?P \ D *)'? –

回答

0

如果您在使用Ruby 2.4及以上的,你可以使用“named_captures”:

line = "matchBegins\/blabla\" = (20, 10);" 
get = line.match(/matchBegins\/(?<match1>\D*)" *= *(?<match2>.*);/) 
hash = get.named_captures 

这是一个Hash(与字符串化的钥匙!),你可以使用fetch指定一个默认值:

hash.fetch('unknownKey', 'default') 

如果您在使用Ruby 1.9.1+您可以使用namescaptures,构建一个散列:

line = "matchBegins\/blabla\" = (20, 10);" 
get = line.match(/matchBegins\/(?<match1>\D*)" *= *(?<match2>.*);/) 
hash = Hash[get.names.zip(get.captures)] 

或者只是救例外:

value = get['unknownKey'] rescue 'default' 

(我觉得这丑陋而这样的代码可能会掩盖其他错误)

不过,说实话,我不知道你的使用情况是什么。为什么你需要从MatchData请求任意键?

+0

Vamsi Krishna,感谢关于捕获/邮编的评论。 –

相关问题