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: