34
votes

From the documentation I understand how =~ operator works to match regex, but I don't understand the general use of this operator.

For example, what does "foo" =~ "foo" mean? How is it different from "foo" == "foo"?

1
=~ validates against a regex, == validates for an exact match. The use of this operator is obvious, you use it to validate a string against a regex.NoDisplayName
"foo" =~ ~/r/foo/ validates against a regex, what I don't understand is what is "foo" =~ "foo". Sorry if the question is not very clear.noscreenname

1 Answers

50
votes

It's not documented on that page, but it's documented in Kernel.=~/2 that when the RHS is a string, =~ checks if LHS contains RHS:

iex(1)> "foo" =~ "f"
true
iex(2)> "foo" =~ "o"
true

It does not implicitly convert RHS to regex:

iex(3)> "foo" =~ "."
false