How to return a boolean value from a regular expression

I cannot understand what I am doing wrong here.

if @calc.docket_num =~ /DC-000044-10/ || @calc.docket_num =~ /DC-67-09/ @calc.lda = true else @calc.lda = false end 

But it seems that @calc.docket_num can be any string and always returns true .

Am I really not doing it right?

+7
source share
3 answers

This is single line:

 @calc.lda = !!(@calc.docket_num =~ /DC-000044-10|DC-67-09/) 

!! forces the response to answer true / false, then you can directly assign your boolean variable.

+32
source

Alternatively, you can use the triple equals ( === ) operator for the Regexp class, which is used to determine equality when using case syntax.

 @calc.lda = /DC-000044-10|DC-67-09/ === @calc.docket_num @calc.lda => true 

Beware

/Regexp/ === String completely different from String === /Regexp/ !!!! The method is not commutative. Each class implements === differently. For this question, the regex should be to the left of === .

To implement Regexp, you can see additional documentation on this subject (starting with Ruby 2.2.1) here .

+4
source

I think the problem is elsewhere in your implementation. Use this code to verify it:

  k = 'random information'

 if k = ~ / DC-000044-10 / ||  k = ~ / DC-67-09 /
   puts 'success'
 else
   puts 'failure'
 end

 => failure
+2
source

All Articles