tags:

views:

37

answers:

1

I've a master text file and exceptions file and I want to match all the words in exception file with master file and increase counter, but the trick is with wildcards.

I'm able to do without wildcards with this:

words = %w(aaa aab acc ccc AAA)
stop = %q(/aa./)

words.each do |x|
    if x.match(/aa./)
     puts "yes for #{x}"        
    else    
     puts "no for #{x}"
    end
end

=>

yes for aaa
yes for aab
no for acc
no for ccc
yes for AAA

Also which would be the best way to go about this, using arrays or some other way.

Edit: Sorry for the confusion. Yes stop has multiple wildcards and I want to match all words based on those wildcards.

words = %w(aaa aab acc ccc AAA)
stop = %q(aa* ac* ab*)

Thanks

+1  A: 

The description of your requirements is really vague. But either the partition or select methods will work for you:

words = %w(aaa aab acc ccc AAA)
re = %r(aa.)i
p words.partition {|word| word.match(re)}  # => [["aaa", "aab", "AAA"], ["acc", "ccc"]]
p words.select {|word| word.match(re)}     # => ["aaa", "aab", "AAA"]

UPDATE

Based on your last comment:

stops= %q(aa* ac* ab*)
stops.split.collect do |wildcard| 
  re = Regexp.new(wildcard, Regexp::IGNORECASE)
  words.select {|word| word.match(re)} 
end
# => [["aaa", "aab", "acc", "AAA"], ["aaa", "aab", "acc", "AAA"], ["aaa", "aab", "acc", "AAA"]]

If those results surprise you, you may want to learn more about regular expressions, which are much different and more powerful than glob-style patterns. Ruby doesn't do glob matching on strings.

glenn jackman
That works for one wildcard expression. What about multiple wildcards?
Senthil
@Senthil, what do you mean? Do you mean `stop` is an array of regexps? You need to update your question and show what you mean by "multiple wildcards".
glenn jackman
Yes. This is what I had original 'stop = %q(aa* ac* ab*)' Thanks
Senthil