5
5

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 5 years have passed since last update.

文字列の部分一致とデフォルト値のイディオム

Last updated at Posted at 2013-01-31

【論理演算子】||のデフォルト値を与えるイディオム の変化形です。
ある文字列に正規表現がマッチするなら一致部分を、そうでないならデフォルト値を与えます。

""[/[A-Za-z]+/] || "default"
#=> "default"
"ATOZ"[/[A-Za-z]+/] || "default"
#=>"ATOZ"
"AtoZ"[/[A-Za-z]+/] || "default"
#=> "AtoZ"
"009"[/[A-Za-z]+/] || "default"
#=> "default"

これはStringオブジェクトに[]を与えると、一致部分もしくは不一致の場合にnilが返却されることを利用しています。[]の引数にはRegexpだけでなく範囲指定や文字列指定も可能です。
instance method String#[]

5
5
0

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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?