Praveenkumar
Praveenkumar

Reputation: 981

How to use a regex without raising a RuboCop warning

This is a regex pattern:

(@location =~ /\A#[a-zA-Z0-9]*\Z/) == 0

RuboCop suggests to use .zero? instead of == 0. But when the regex does not match, it will return nil. Then nil.zero? will throw an "undefined method .zero? for nil" error. Any better way to do regex in ruby?

Upvotes: 3

Views: 533

Answers (5)

petkov.np
petkov.np

Reputation: 520

I'd propose the following solution:

/\A#[a-zA-Z0-9]*\Z/.match?(@location)

This will safeguard the case when @location is nil and will make rubocop happy.

Upvotes: 0

Drenmi
Drenmi

Reputation: 8777

This is a known false positive that happens because #=~ does not adhere to the principle of duck typing, i.e. it has incompatible return value signatures.

There are some good answers already regarding how you can rewrite your code, and this is really what RuboCop is all about, but sometimes rewriting will result in code that is worse. For those cases, the generic way of marking false positives is to use a disable:

(@location =~ /\A#[a-zA-Z0-9]*\Z/) == 0 # rubocop:disable Style/NumericPredicate

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

You are trying to solve a problem that does not exist. Because of anchor \A there are exactly two possible returns: 0 and nil. That said:

!(@location =~ /\A#[a-zA-Z0-9]*\Z/).nil?

or even

!!(@location =~ /\A#[a-zA-Z0-9]*\Z/)

or even better:

@location[/\A#[a-zA-Z0-9]*\Z/]

Upvotes: 3

Eric Duminil
Eric Duminil

Reputation: 54283

Not every tip from rubocop is a good tip.

In Ruby 2.4 :

@location.match? /\A#[a-zA-Z0-9]*\Z/

By the way, do you want /\Z/ (a line ending at the end of the string) or /\z/ (end of the string)?

Upvotes: 8

ndnenkov
ndnenkov

Reputation: 36110

Assuming you run ruby 2.3.0+:

(@location =~ /\A#[a-zA-Z0-9]*\Z/)&.zero?

Also as per your specific case, you seem to want to check that you have an exact match. Hence you don't need to check that the starting position is exactly 0 at all:

do_something if @location =~ /\A#[a-zA-Z0-9]*\Z/

Upvotes: 4

Related Questions