LoginSignup
19
19

More than 5 years have passed since last update.

配列を渡して正規表現オブジェクトをつくる

Last updated at Posted at 2014-08-18

Regexp.union以前

どれかにマッチする正規表現を動的に作りたいという時。
なにも考えずに普通に書くと、

string_regexp.rb
words = %w(foo bar baz)
regexp = Regexp.new(words.join('|'))

こんな風に書くと思います。(僕はそうでした)

悪くないけど

"foo""bar""baz" のいずれかにマッチする
正規表現である"foo|bar|baz"という文字列を組み立ててから、
それをRegexp.newに渡して正規表現オブジェクトを得る。
というのが少し遠回りですね。

そこでRegexp.union

regexp_union.rb
words = %w(foo bar baz)
regexp = Regexp.union(words)

一度、文字列で正規表現を組み立てたりせず
直接配列を渡して、正規表現オブジェクトを作っているので
Regexp.unionを使わないコードと比べて、より直感的になったのではないでしょうか。

引数の配列には正規表現オブジェクトも入れられる

regexp_union_regexp.rb
parts = [/^foo$/, /^bar/, /baz$/]
regexp = Regexp.union(parts)

文字列(というか多分 to_s to_strできるオブジェクト)だけでなく
正規表現そのものを要素に持つ配列も渡すことができます。

参考

class Regexp

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