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?(str
As I wanted this to work generally, and not just for any specific project, I do not want to modify the environment at all.
I was able to get it to work by simply using the return value from the normal match
method as a conditional. Tested both the positive and negative case on this sample string:
irb(main):014:0> if "123".match(/.2./); puts "worked"; end
worked
=> nil
irb(main):015:0> if "123".match(/.3./); puts "worked"; end
=> nil
To make it return true/false switch the position of pattern and string and use case equality ===
def has_regex?(string)
pattern = /something/i
return pattern === string
end
I absolutely needed it to return true boolean value and digged around. It is actually documented in regexp class http://www.ruby-doc.org/core-2.1.3/Regexp.html#method-i-3D-3D-3D
If you want the put the pattern in a method, you can just do
def has_my_pattern(st)
st =~ /pattern/
end
Or, perhaps better, put the pattern in a class variable instead?
For Ruby >= 2.4 or Rails, you can do:
regexp.match?(string)
For anyone's future reference, double bangs are frowned upon from bbatsov's ruby style guide. Instead of using a double bang, just check if the value isn't nil. If the value isn't nil, it exists.
Instead of doing this:
def has_regex?(string)
!!(string =~ /something/i)
end
You can always do this:
def has_regex?(string)
!(string =~ /something/i).nil?
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