Topic: Using a variable in an Array.select statement

this seems like such a simple thing to do but i can't get it to work.

Example:

new_array =  %w{"first_entry" "second_entry"}
puts new_array.select {|v| v=~ /entry/}

This will select and print all entries in my array that contain the string "entry".

But now I need to use a variable to search the array and i can't get it to work because it seems that a select statement is looking for a regular expression only.

I tried a few variations of the following but can't get it to work:

search_variable =  "entry"
new_array =  %w{"first_entry" "second_entry"}
puts new_array.select {|v| v=~ /"#{search_variable}"/}

can someone please show me what I'm doing wrong?

thanks

jack

Last edited by jackster (2010-11-28 15:27:43)

Re: Using a variable in an Array.select statement

I solved the problem with the following:

search_variable =  "entry"
new_array =  %w{"first_entry" "second_entry"}
puts new_array.select {|v| v=~ /#{search_variable}/}

thanks
jack

Re: Using a variable in an Array.select statement

You could try the following

Array.select {|v| v =~ Regexp.new(variable)}