Skip to main content
edited for readability
Source Link
the Tin Man
  • 160.1k
  • 44
  • 218
  • 306

Expanding on Clint Pachl's answer:

Regex matching in Ruby returns nilnil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only nilnil and the boolean expression falsefalse evaluate to false. Everything else, including an empty arrayArray, empty hashHash, or the integerInteger 0, evaluates to true.

That's why the /foo//foo/ example above works, and why.

if "string" =~ /regex/

works as expected. Only, only entering the 'true' part of the ifif block if a match occurred.

Expanding on Clint Pachl's answer:

Regex matching in Ruby returns nil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty array, empty hash, or the integer 0, evaluates to true.

That's why the /foo/ example above works, and why

if "string" =~ /regex/

works as expected. Only entering the 'true' part of the if block if a match occurred.

Expanding on Clint Pachl's answer:

Regex matching in Ruby returns nil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty Array, empty Hash, or the Integer 0, evaluates to true.

That's why the /foo/ example above works, and why.

if "string" =~ /regex/

works as expected, only entering the 'true' part of the if block if a match occurred.

Source Link
acib708
  • 1.6k
  • 1
  • 13
  • 24

Expanding on Clint Pachl's answer:

Regex matching in Ruby returns nil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty array, empty hash, or the integer 0, evaluates to true.

That's why the /foo/ example above works, and why

if "string" =~ /regex/

works as expected. Only entering the 'true' part of the if block if a match occurred.