Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Created January 14, 2016 08:12
Show Gist options
  • Select an option

  • Save YumaInaura/75da9d1b3cd8912c451b to your computer and use it in GitHub Desktop.

Select an option

Save YumaInaura/75da9d1b3cd8912c451b to your computer and use it in GitHub Desktop.
Ruby | 正規表現でのキャプチャがマッチしなかった場合の NoMethodError に対策する ref: http://qiita.com/Yinaura/items/d40ea26f0f69afc92a81
'Welcome to my DIRTY house.'.match(/(?<match>DIRTY)/)[:match]
# => "DIRTY"
'Welcome to my DIRTY house.'.match(/(?<match>CLEAN)/)[:match]
# NoMethodError: undefined method `[]' for nil:NilClass
nil.to_h
# => {}
'Welcome to my DIRTY house.'.match(/(?<match>CLEAN)/).to_h[:match]
# => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment