🖥
Ruby | We cope with NoMethodError when it does not match in regular ex
problem
When using capture with regular expressions. You can back reference the matched value by hash.
'Welcome to DIRTY House.'.match(/(?<match>DIRTY)/)[:match] # => "DIRTY"
However, if it does not match, a NoMethodError will occur.
'Welcome to DIRTY House.'.match(/(?<match>CLEAN)/)[:match] # => NoMethodError: undefined method `[]' for nil:NilClass
Solution
As a countermeasure, if nothing is found, substitute an empty array with ||
.
('Welcome to DIRTY House.'.match(/(?<match>CLEAN)/) || {})[:match] # => nil
Now returns nil instead of NoMethodError.
environment
- Ruby 2.0.0
Original by
Ruby | 正規表現のキャプチャでマッチしなかった時の NoMethodError に対策する
About
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-04-16
Discussion