This question already has answers here:
What is the "=~" operator in Ruby?
(7 answers)
Closed 8 years ago.
In ruby, I read some of the operators, but I couldn't find =~. What is =~ for, or what does it mean? The program that I saw has
regexs = (/\d+/)
a = somestring
if a =~ regexs
I think it was comparing if somestring equal to digits but, is there any other usage, and what is the proper definition of the =~ operator?
The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.
/mi/ =~ "hi mike" # => 3
"hi mike" =~ /mi/ # => 3
"mike" =~ /ruby/ # => nil
You can place the string/regex on either side of the operator as you can see above.
This operator matches strings against regular expressions.
s = 'how now brown cow'
s =~ /cow/ # => 14
s =~ /now/ # => 4
s =~ /cat/ # => nil
If the String matches the expression, the operator returns the offset, and if it doesn't, it returns nil. It's slightly more complicated than that: see documentation here; it's a method in the String class.
=~ is an operator for matching regular expressions, that will return the index of the start of the match (or nil if there is no match).
See here for the documentation.
Related
This question already has answers here:
What is the !=~ comparison operator in ruby?
(2 answers)
Closed 2 years ago.
I am modifying an existing ruby code. It has the following lines of code. Can somebody tell me what is going on.
if string ==~ /^ABC/
do-something
elsif string == "some string"
do-something
else
do-something
end
What is the if condition doing here. I googled for ==~ operator and found nothing.
I just found explanation for =~, which means matching strings with regular expressions.
So, if the above if condition has single = , it means check if string starts with ABC. But that is not happening when i run the code. Even though string starts with ABC, it doesn't go into if.
I am not sure if it is a mistake or intentional usage of ==~
The unary ~ operator has higher precedence than == or =~ so this:
string ==~ /^ABC/
is just a confusing way of writing:
string == (~/^ABC/)
But what does Regexp#~ do? The fine manual says:
~ rxp → integer or nil
Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.
and $_ is "The last input line of string by gets or readline." That gives us:
string == (/^ABC/ =~ $_)
and that doesn't make any sense at all because the right hand side will be a number or nil and the left hand side is, presumably, a string. The condition will only be true if string.nil? and the regex match fails but there are better ways to doing that.
I think you have two problems:
==~ is a typo that should probably be =~.
Your test suite has holes, possibly one hole that the entire code base fits in.
See also What is the !=~ comparison operator in ruby? for a similar question.
I saw this on a screencast and couldn't figure out what it was. Reference sheets just pile it in with other operators as a general pattern match operator.
It matches string to a regular expression.
'hello' =~ /^h/ # => 0
If there is no match, it will return nil. If you pass it invalid arguments (ie, left or right-hand sides are not correct), it will either throw a TypeError or return false.
From ruby-doc :
str =~ obj => fixnum or nil
Match—If obj is a Regexp, use it as a pattern to match against str, and returns the offset position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false.
"cat o' 9 tails" =~ /\d/ #=> 7
"cat o' 9 tails" =~ 9 #=> false
Well, the reference is correct, it is the "matches this regex" operator.
if var =~ /myregex/ then something end
As the other answers already stated, =~ is the regular expression vs string match operator.
Note: The =~ operator is not commutative
Please consider the note below from the ruby doc site, as I have seen yet only the first form
str =~ regexp
used in the other answers:
Note: str =~ regexp is not the same as regexp =~ str. Strings captured
from named capture groups are assigned to local variables only in the
second case.
Here is the documentation for the second form: link
Regular expression string matching. Here's a detailed list of operators: http://phrogz.net/programmingruby/tut_expressions.html#table_7.1
Regular expression string matching:
puts true if url =~ /google.com/
You can read '=~' as 'is matching'.
I believe this is a pattern matching operator used with regex.
This question already has answers here:
How to compare strings ignoring the case
(5 answers)
Closed 7 years ago.
I want to test 2 strings for equality in Ruby in a case insensitive manner.
In languages, such as Fantom, you simply write:
string1.equalsIgnoreCase(string2)
What's the idiomatic way to do this in Ruby?
You can use casecmp
"Test".casecmp("teST")
=> 0
"Test".casecmp("teST2")
=> -1
So to test for equality, you can do:
if str.casecmp(str2).zero?
# strings are equal
end
Though there is casecmp:
0 == s1.casecmp(s2) # strings equal
I personally prefer
s1.downcase == s2.downcase
You can convert the strings to lowercase and then compare
a.downcase == b.downcase
Or, if you prefer, to uppercase
a.upcase == b.upcase
You can use String#match method :
s = "Test"
s.match(/teST/i) # => #<MatchData "Test">
s.match(/teST2/i) # => nil
Remember in Ruby all objects are has the truth value, except nil and false. So you can use this trick also to perform conditional testing.
Is there a way to check in Ruby whether the string "1:/2" is contained within a larger string str, beside iterating over all positions of str?
You can use the include? method
str = "wdadwada1:/2wwedaw"
# => "wdadwada1:/2wwedaw"
str.include? "1:/2"
# => true
A regular expression will do that.
s =~ /1:\/2/
This will return either nil if s does not contain the string, or the integer position if it does. Since nil is falsy and an integer is truthy, you can use this expression in an if statement:
if s =~ /1:\/2/
...
end
The regular expression is normally delimited by /, which is why the slash within the regular expression is escaped as \/
It is possible to use a different delimiter to avoid having to escape the /:
s =~ %r"1:/2"
You could use other characters than " with this syntax, if you want.
The simplest and most straight-forward is to simply ask the string if it contains the sub-string:
"...the string 1:/2 is contained..."['1:/2']
# => "1:/2"
!!"...the string 1:/2 is contained..."['1:/2']
# => true
The documentation has the full scoop; Look at the last two examples.
I saw this on a screencast and couldn't figure out what it was. Reference sheets just pile it in with other operators as a general pattern match operator.
It matches string to a regular expression.
'hello' =~ /^h/ # => 0
If there is no match, it will return nil. If you pass it invalid arguments (ie, left or right-hand sides are not correct), it will either throw a TypeError or return false.
From ruby-doc :
str =~ obj => fixnum or nil
Match—If obj is a Regexp, use it as a pattern to match against str, and returns the offset position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false.
"cat o' 9 tails" =~ /\d/ #=> 7
"cat o' 9 tails" =~ 9 #=> false
Well, the reference is correct, it is the "matches this regex" operator.
if var =~ /myregex/ then something end
As the other answers already stated, =~ is the regular expression vs string match operator.
Note: The =~ operator is not commutative
Please consider the note below from the ruby doc site, as I have seen yet only the first form
str =~ regexp
used in the other answers:
Note: str =~ regexp is not the same as regexp =~ str. Strings captured
from named capture groups are assigned to local variables only in the
second case.
Here is the documentation for the second form: link
Regular expression string matching. Here's a detailed list of operators: http://phrogz.net/programmingruby/tut_expressions.html#table_7.1
Regular expression string matching:
puts true if url =~ /google.com/
You can read '=~' as 'is matching'.
I believe this is a pattern matching operator used with regex.