0
0

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

if文でinclude?(xxx)のor条件を連続で何度も書くのを、簡潔でシュッとした書き方にする。

Last updated at Posted at 2021-06-07

備忘録用。

前提条件

例えば、「メッセージ文の中に、東京・神奈川・千葉・埼玉が含まれるか」の場合、

if msg.include?("tokyo") || msg.include?("kanagawa") || msg.include?("chiba") || msg.include?("saitama")

となってしまい、ちょっと見づらい。
少し見やすい書き方として、

if msg.include?( "tokyo" || "kanagawa"  || "chiba" || "saitama" ) 

なんて書き方も悪くないかもしれないけど、チェックする県が増えたらどんどん横長ブサイクになってしまう。

.any? とブロックを使えばシュッとなる

list = [ "tokyo",
         "kanagawa",
         "chiba",
         "saitama"
       ]

if list.any? { |n| msg.include?(n) }

「msg.include?(n) がtrueとなる要素」が1つでもlistにあればtrueを返す。

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?