Trip
Trip

Reputation: 27114

How to return a boolean value from a regex

I can't quite figure out what I'm 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 whatsoever and it always returns as true.

Am I not doing this right?

Upvotes: 7

Views: 7797

Answers (3)

Curley
Curley

Reputation: 1621

Alternatively you could use the triple equals (===) operator for the Regexp class which is used for determining equality when using case syntax.

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

BEWARE

/Regexp/ === String is totally different than String === /Regexp/!!!! The method is not commutative. Each class implements === differently. For the question above, the regular expression has to be to the left of ===.

For the Regexp implementation, you can see more documentation on this (as of Ruby 2.2.1) here.

Upvotes: 4

Mark Thomas
Mark Thomas

Reputation: 37517

This is a one-liner:

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

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

Upvotes: 32

Pan Thomakos
Pan Thomakos

Reputation: 34350

I think the issue is somewhere else in your implementation. Use this code to check it:

k = 'random information'

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

=> failure

Upvotes: 2

Related Questions