Re: Doing an AND in regexp char class
by 7stud -- other posts by this author
May 9 2008 12:19AM messages near this date
Re: Doing an AND in regexp char class
|
Re: Doing an AND in regexp char class
Joel VanderWerf wrote:
> Todd Benson wrote:
> >>>
> >>> Thanks,
> >> p 'foobar'.all_chars?('')
> >>
> >>
> >>
> >> cfp:~ > ruby a.rb
> >> true
> >> false
> >> false
> >
> > Cool :) #tr is one of those useful methods I somehow consistently forget about.
>
> But it can be done with regex, right? It's just more elegant with tr.
>
> class String
> def all_chars? chars
> if chars.empty?
> empty?
> else
> /\A[#{chars}]*\z/ === self
> end
> end
> end
>
> p 'foobar'.all_chars?('rabof') # => true
> p 'foobar'.all_chars?('abc') # => false
> p 'foobar'.all_chars?('') # => false
Your method doesn't work, which can clearly be seen in these examples:
strs = ["aaa", "bbb", "ccc"]
chars = "abc"
strs.each do |str|
if /\A[#{chars}]*/ =~ str
print str, " - yes"
puts
else
print str, " - no"
puts
end
end
--output:--
aaa - yes
bbb - yes
ccc - yes
It should be clear from the output that even though the string "aaa"
passes your test, it is not true that all the characters in the string
"abc" appear in in the string "aaa".
--
Posted via http://www.ruby-forum.com/.
Thread:
Todd Benson
Rick DeNatale
Ara.T.Howard
Pit Capitain
Todd Benson
Joel VanderWerf
7stud --
David A. Black
7stud --
Todd Benson
David A. Black
Joel VanderWerf
Todd Benson
David A. Black
Joel VanderWerf
David A. Black
Ara.T.Howard
Robert Dober
|