examples/types_custom.rb
Use match?
instead of =~
when MatchData
is not used. Open
Open
raise Optimist::CommandlineError, "option '#{self.name}' should be formatted as a zipcode" unless param_string=~ ZipCode::REGEXP
- Read upRead up
- Exclude checks
In Ruby 2.4, String#match?
, Regexp#match?
and Symbol#match?
have been added. The methods are faster than match
.
Because the methods avoid creating a MatchData
object or saving
backref.
So, when MatchData
is not used, use match?
instead of match
.
Example:
# bad
def foo
if x =~ /re/
do_something
end
end
# bad
def foo
if x.match(/re/)
do_something
end
end
# bad
def foo
if /re/ === x
do_something
end
end
# good
def foo
if x.match?(/re/)
do_something
end
end
# good
def foo
if x =~ /re/
do_something(Regexp.last_match)
end
end
# good
def foo
if x.match(/re/)
do_something($~)
end
end
# good
def foo
if /re/ === x
do_something($~)
end
end
Do not mix named captures and numbered captures in a Regexp literal. Open
Open
REGEXP = %r/^(?<zip>[0-9]{5})(\-(?<plusfour>[0-9]{4}))?$/
- Read upRead up
- Exclude checks
Do not mix named captures and numbered captures in a Regexp literal because numbered capture is ignored if they're mixed. Replace numbered captures with non-capturing groupings or named captures.
Example:
# bad
/(?<foo>FOO)(BAR)/
# good
/(?<foo>FOO)(?<bar>BAR)/
# good
/(?<foo>FOO)(?:BAR)/
# good
/(FOO)(BAR)/</foo></bar></foo></foo>