🖥

Ruby | We cope with NoMethodError when it does not match in regular ex

2019/04/16に公開

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

About this translattion

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion