Search code examples
ruby-on-railsregexrubyignore-case

Rails Regexp::IGNORECASE while matching exact options with number options also included in the results


I want to match the options between two arrays with exact string.

options = ["arish1", "arish2", "ARISH3", "arish 2", "arish"]
choices = ["Arish"]
final_choice = options.grep(Regexp.new(choices.join('|'), Regexp::IGNORECASE))
p final_choice

Output:
 ["arish1", "arish2", "ARISH3", "arish 2", "arish"]

but it should be only match "arish"

Solution

  • You need to use

    final_choice = options.grep(/\A(?:#{Regexp.union(choices).source})\z/i)
    

    See the Ruby online demo.

    Note:

    • A regex literal notation is much tidier than the constructor notation
    • You can still use a variable inside the regex literal
    • The Regexp.union method joins the alternatives in choices using | "or" regex operator and escapes the items as necessary automatically
    • \A anchor matches the start of stirng and \z matches the end of stirng.
    • The non-capturing group, (?:...), is used to make sure the anchors are applied to each alternative in choices separately.
    • .source is used to obtain just the pattern part from the regex.