[Ruby] Creating Regular Expressions from Arrays with Regexp.union

Tadashi Shigeoka ·  Sun, March 3, 2013

In Ruby, you can create regular expressions from arrays using Regexp.union.

# Check if image file extension format is correct
# @param [String] File extension
# @return [Boolean] Valid: true, Invalid: false
def valid_image_file_extension?(file_extension)
  regex = Regexp.union(extension_white_list)
  (file_extension =~ regex) ? true : false
end

# List of allowed extensions
def extension_white_list
  %w(jpg jpeg gif png)
end

Regexp - Rubyリファレンスマニュアル

Regexp.unionで配列から正規表現をつくる方法 - memo.yomukaku.net

That’s all from the Gemba.