20

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 Jun 21 '17 at 9:07
  • "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 Jun 21 '17 at 9:11
33

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
  • I haven't seen that there was a more complete documentation, thanks. – noscreenname Jun 21 '17 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.