What is the proper syntax for a method that checks a string for a pattern, and returns true or false if the regex matches?
Basic idea:
def has_regex?(string)
pattern = /something/i
return string =~ pattern
end
Use case:
if has_regex?("something")
# woohoo
else
# nothing found: panic!
end
=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.
Matches a whitespace character: /[ \t\r\n\f]/. Matches non-whitespace: /[^ \t\r\n\f]/. Matches a single word character: /[A-Za-z0-9_]/. Matches a non-word character: /[^A-Za-z0-9_]/.
In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .
A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.
In the question you said:
... method that checks a string for a pattern, and returns true or false if the regex matches
As johannes pointed out String=~
returns nil
if the pattern did not match and the position in the string where the matched word stared otherwise. Further he states in Ruby everything except nil
and false
behave like true
. All of this is right.
However, they are not exactly true
or false
. Therefore, the last step is to coerce the value to be a Boolean
. This is achieved by wrapping the result in double bangs returns a true
.
def has_regex?(string)
!!(string =~ /something/i)
end
Your code looks fine, but you could write it even smaller.
The return value of String#=~
behaves this way:
nil
if the pattern did not matchIn Ruby everything except nil
and false
behaves like true
in a conditional statement so you can just write
if string=~ pattern
# do something
else
# panic
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With