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.
Related
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.
I am writing a 6502 assembler in Ruby. I am looking for a way to validate hexadecimal operands in string form. I understand that the String object provides a "hex" method to return a number, but here's a problem I run into:
"0A".hex #=> 10 - a valid hexadecimal value
"0Z".hex #=> 0 - invalid, produces a zero
"asfd".hex #=> 10 - Why 10? I guess it reads 'a' first and stops at 's'?
You will get some odd results by typing in a bunch of gibberish. What I need is a way to first verify that the value is a legit hex string.
I was playing around with regular expressions, and realized I can do this:
true if "0A" =~ /[A-Fa-f0-9]/
#=> true
true if "0Z" =~ /[A-Fa-f0-9]/
#=> true <-- PROBLEM
I'm not sure how to address this issue. I need to be able to verify that letters are only A-F and that if it is just numbers that is ok too.
I'm hoping to avoid spaghetti code, riddled with "if" statements. I am hoping that someone could provide a "one-liner" or some form of elegent code.
Thanks!
!str[/\H/] will look for invalid hex values.
String#hex does not interpret the whole string as hex, it extracts from the beginning of the string up to as far as it can be interpreted as hex. With "0Z", the "0" is valid hex, so it interpreted that part. With "asfd", the "a" is valid hex, so it interpreted that part.
One method:
str.to_i(16).to_s(16) == str.downcase
Another:
str =~ /\A[a-f0-9]+\Z/i # or simply /\A\h+\Z/ (see hirolau's answer)
About your regex, you have to use anchors (\A for begin of string and \Z for end of string) to say that you want the full string to match. Also, the + repeats the match for one or more characters.
Note that you could use ^ (begin of line) and $ (end of line), but this would allow strings like "something\n0A" to pass.
This is an old question, but I just had the issue myself. I opted for this in my code:
str =~ /^\h+$/
It has the added benefit of returning nil if str is nil.
Since Ruby has literal hex built-in, you can eval the string and rescue the SyntaxError
eval "0xA" => 10
eval "0xZ" => SyntaxError
You can use this on a method like
def is_hex?(str)
begin
eval("0x#{str}")
true
rescue SyntaxError
false
end
end
is_hex?('0A') => true
is_hex?('0Z') => false
Of course since you are using eval, make sure you are sending only safe values to the methods
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.
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.
I don't know how pattern matching works in Ruby 2.
I have the following value, targetfilename = /mnt/usb/mpeg4Encoded.mpeg4
My pattern matching if-else is thus:
if (targetfilename.match(/^\//))
puts "amit"
else
puts "ramit"
The output is ramit.
I don't understand how this pattern matching works though.
if targetfilename.match(/^V/)
puts "amit"
else
puts "ramit"
end
# result:
# "amit"
Why is this? This is because targetfilename.match(/^V/) outputs a Matchdata object (click on the link for a full description of this object). This is an object that contains all of the information that is in the "matching". If there is no match, no MatchData object is returned, because there's nothing to return. Instead, you get nil.
When you use if, if it tries to compare a nil, it treats it the same way as false.
Basically, any "actual" value (besides false) is treated the same way as true. Basically, it's asking
if (there's anything here)
do_this
else
do_something_else
end
Again, let me reiterate:
If the thing after if is either false or nil, the if statement resolves to the "else".
If it's anything else, it resolves as if it had gotten a "true" statement.
Regular Expressions
/^V/ is what is called a "Regular Expression"; the // is a Regexp literal the same way that the "" is a String literal, and Regexps are represented by the Regexp class the same way that strings are represented by the String class.
The actual "regular expression" is what's between the slashes -- ^V. This is saying:
^: the start of a string
V: a capital letter V
So, /^V/ will match any cases of the capital letter "V" at the beginning of a string.
What else can you put in a regular expression? What are the special characters? Try this regexp cheat sheet
Also, some great tools:
Rubular -- enter in your regular expression, and then a same text, and see what matches.
Strfriend -- enter in a regular expression and see it "visually" represented.