Techioz Blog

文字列が複数の文字のいずれかで終わるかどうかを確認する方法

概要

こんな発言があります。

string_tokens[-1].ends_with?(",") || string_tokens[-1].ends_with?("-") || string_tokens[-1].ends_with?("&")

すべてのトークン (「,」、「-」、「&」) を定数に入れて、「文字列はこれらの文字のいずれかで終わるか」を尋ねるために上記を簡略化したいのですが、方法がわかりませんそれをするために。

解決策

はい。

CONST = %w|, - &|.freeze
string_tokens[-1].end_with?(*CONST)

使用法:

'test,'.end_with?(*CONST)
#=> true
'test&'.end_with?(*CONST)
#=> true
'test-'.end_with?(*CONST)
#=> true

String#end_with? は複数の引数を受け入れるため、 * (スプラット演算子) を使用して複数の引数を String#end_with? に渡します。