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"
You need to use
final_choice = options.grep(/\A(?:#{Regexp.union(choices).source})\z/i)
See the Ruby online demo.
Note:
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.(?:...)
, 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.