Jose Villalta
Jose Villalta

Reputation: 1479

Ruby variable regular expression in Array Select

I'm trying to exclude elements from an array of strings using array.select. I have this method:

def filter_out_other_bad_vals(array_of_strs, things_i_want)
  array_of_strs = array_of_strs.select { |line| /"#{things_i_want}"/.match(line) } 
end 

I want to pass a string as a variable things_i_want. But this does not return any matches:

array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
pattern = 'want_this'
array = filter_out_other_bad_vals(array, pattern)

This returns an empty array. But if I hardcode the value in the match expression, I get what I want.

def filter_out_other_bad_vals(array_of_strs, things_i_want)
  array_of_strs = array_of_strs.select { |line| /want_this/.match(line) } 
end 

How do I put a variable in the regex? What am I doing wrong?

I could just traverse the array, check each item, and then save the value in another array, but that's not very ruby-like, is it?

Upvotes: 1

Views: 1950

Answers (1)

mrzasa
mrzasa

Reputation: 23327

You include quotes in regex definition:

 /"#{things_i_want}"/

remove them and it should work:

/#{things_i_want}/

EDIT: By the way, you don't have to use regex for exact matching, you can use equality check (==) or #include? depending if you need a string to be equal to thing you want or just include it:

> array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
> array.select{|line| line == 'want_this'}
# => ["want_this", "want_this", "want_this"]
> array.select{|line| line.include? 'want_this'}
# => ["want_this", "want_this", "want_this"]

Upvotes: 2

Related Questions