Alle 18:29, martedì 23 gennaio 2007, JT Kimbell ha scritto:
Hey everyone,
Right now I have an array of terms and I want to delete/find a term
using pattern matching.
For example, I have the following array (this is a very simple example).
x = ["dog", "cat", "moose"]
x.include?(/dog/) returns false.
Now, I understand regular expressions, and can usually get one that
works, but perhaps I am using them wrong in ruby?
Anyway, my question is if I can use regex to find an array element(s)?
Thanks,
JT
Your code doesn't work because the array contains Strings, and regular
expression are of class Regexp, not of class String. If you look at the
documentation for the Regexp class, you'll see that the operator == (used by
include?) for Regexp always returns false when the right side is not a
regexp. In other words, the operator == is unrelated to regexp matching. To
do what you want, you should can use the grep or the any? method in the
Enumerable module.
* grep returns an array with the elements which match (using the operator ===
this time) the given pattern. In your case:
x.grep /dog/
=>['dog']
You should then use the empty? on the returned array to see whether there's a
match:
x.grep(/dog/).empty?
This returns true if there's no match and false if there's at least one match
* any? passes each element of the array to the supplied block and returns true
if the block returns true for at least one element:
x.any?{|string| string.match /dog/}
Stefano