— Feb 05, 2013
Update: After writing this, I discovered a better method
for solving this problem. I thought it worth going ahead and publishing this
post since I took the time to write it. Maybe there’s some good buried in here
somewhere. I think my favorite part of the below idea is its use of
uses short-circuited logic to quickly match during the injection loop. Live and
For a recent Rails project, I needed to exclude some items from an
problem was I needed to exclude items that matched certain patterns rather than
the exact strings. So
my_arr - excluded_items was out.
Say we have an array that looks like this:
And we want to exclude any elements containing the string
This method will see if the any of the array’s items match the given string. It uses each value of the array as a regular expression against the given value.
The above problem can be solved by:
You can also provide a “format” (for lack of a better word) for the regular expression that will be used to match items.
You could for example find if a given string ended in a number of suffixes.
In this example, the second value
"something_with_this_also" is not excluded
because it does not end with
"_with" as specified by the format
I must admit, something about this solution doesn’t quite feel “right”, but it was at least a fun little experiment. Feel free to tell me if you think I’m way out in left field over this solution. :)comments powered by Disqus