2017-07-13 52 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,感謝關於捕獲/郵編的評論。 –

相關問題