3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby | 正規表現のキャプチャでマッチしなかった時の NoMethodError に対策する

Last updated at Posted at 2016-01-14

問題

正規表現でキャプチャを使うと。
マッチした値をハッシュで後方参照できる。

'Welcome to DIRTY House.'.match(/(?<match>DIRTY)/)[:match]

# => "DIRTY"

しかしマッチしなかった場合には NoMethodError が起きてしまう。

'Welcome to DIRTY House.'.match(/(?<match>CLEAN)/)[:match]

# => NoMethodError: undefined method `[]' for nil:NilClass

解決

対策として、 何も見つからなかった場合は || で空の配列を代入する。

('Welcome to DIRTY House.'.match(/(?<match>CLEAN)/) || {})[:match]

# => nil

NoMethodError ではなく nil が返るようになった。

環境

  • Ruby 2.0.0

チャットメンバー募集

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

メンター受付

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?