What is the "=~" operator in Ruby? - ruby

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.

Related

Ruby, True/false regex

So I've got an issue where my regex looks like this: /true|false/.
When I check the word falsee I get a true from this regex, is there a way to just limit it to the exact true or false words?
Use this regex:
/^(true|false)$/
It will match the beginning and end of the test string with ^ and $, respectively, so nothing else can be in the string (exact match).
See live example at Regex101.
UPDATE (see #w0lf's comment): The parentheses are to isolate the true|false clause so that they are not grouped incorrectly. (This also puts the true or false match in the first capturing group, but since it seems that you are only matching and not capturing an output, this should not make a difference).
Alternatively, if you simply want to match two values, there are easier ways in Ruby. #SimoneCarletti suggests one. You can also use the basic == or eql? operators. Try running the following script to see that these all work:
values = ["true", "false", "almosttrue", "falsealmost"]
values.each do | value |
puts value
# these three are all equivalent
puts "match with if" if value == "true" || value == "false"
puts "match with equals?" if (value.eql? "true") || (value.eql? "false")
puts "match with regex" if /^(true|false)$/.match value
puts
end
You need to use the ^ and $ anchors:
/^(true|false)$/
Edit: As Cary pointed out in the comments, the pattern above will also match multiline strings that happen to contain a line with true or false. To avoid this, use the \A and \z delimiters that match the beginning and end of string respectively:
/\A(true|false)\z/
Try out
/^(true|false)$/
where ^ is the start of a line and $ the end.
You can use
/^(true|false)$/
or even better
/\A(true|false)\z/
that will match the beginning and end of the string (instead of line). If you only need to match for whose words, it may be more efficient to use a simple array and include?:
%w( true false ).include?(value)

Ruby: =~ symbol - what does it mean [duplicate]

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.

How to ignore uppercase using start_with?

Is there a better way to ignore uppercase than this?
"Hello".start_with?("hell","Hell") #=> true
I want to check if a string element in an array starts with another string ignoring uppercase, like LIKE % in MySQL.
I would do something like this:
'Hello'.upcase.start_with?('HELL')
Another approach to the same problem. That's equivalent to do something like UPPER(column) like 'SOMETHING%' in SQL.
You could use a regular expression with String#=~:
"Hello" =~ /^hell/i #=> 0
"hELLO" =~ /^hell/i #=> 0
"world" =~ /^hell/i #=> nil
Since 0 is truthy and nil is falsy this can be used in an if clause:
if str =~ /^hell/i
# starts with hell
end
I think the best is to use Ruby's regex matching with ignore case flag:
'Hello'.match /^hell/i
The '^' designates the start of the string. Without it would match 'hell' anywhere in the string. And the last 'i' is just a regex flag to indicate matching with ignore case set.
You can find more info on Ruby Regex API here:
http://www.regular-expressions.info/ruby.html

String containment

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.

ruby operator "=~" [duplicate]

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.

Resources