简体   繁体   中英

What do =~ and /\ mean in Ruby?

I've been teaching myself Ruby and for a certain problem I'm trying to solve I notice a lot of people are using =~ and /\\ in their code. I'm not really sure how they work and would just like an explanation. For example I was looking at someones code for this Pig Latin translator and this is the first time I'm seeing these being used.

def piglatin(word)
   if word =~ (/\A[aeiou]/i)
      word = word + 'ay'
   elsif word =~ (/\A[^aeiou]/i)
      match = /\A[^aeiou]/i.match(word)
      word = match.post_match + match.to_s + 'ay'
   end
word
end

I'm just confused about the /\\ slashes and the =~

=~ is known as the "match operator" and can be used to match a string against a regular expression.

The /\\ is actually part of two separate things. / denotes the start of a regular expression and \\A is known as an "anchor" and is saying "match from the beginning of the string."

edit: This is a link to the documentation that should help you understand more code like you posted.

thank you to Wayne Conrad for a correction on '/\\'

=~ is Ruby's pattern-matching operator.

It matches a regular expression on the left to a string on the right.

If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

/abc/ =~ "abcdef"

In this case, the expression returns 0, because that is the index of the first match of "abc" in the string.

/xyz/ =~ "abcdef"

returns nil because "xyz" cannot be found anywhere in the string.

As for /\\ :

/     Defines the start and end of a regular expression
\     References a regular expression

For example:

\d => Matches all digits

The equal-tilde operator in Ruby is the “match” operator. It take an regular expression on the left hand side and the string to match on the right hand side. The expression:

/or/ =~ “Hello World”

will return 7 because a match is found on index 7 of the string. The index starts at 0.

The expression:

/abc/ =~ “Hello World”

will return nil because there is no match.

The use of /\\A and =~ aside, that code is not written well, so don't emulate it. This is a bit more Ruby-like:

def piglatin(word)
  if word[/\A[aeiou]/i]
    word + 'ay'
  else
    word[1..-1] + word[0] + 'ay'
  end
end

piglatin('apple')   # => "appleay"
piglatin('banana')  # => "ananabay"

For this purpose, ^ would have worked as well as \\A as they're both "beginning of..." anchors. These are from the Anchors definitions :

  • ^ - Matches beginning of line
  • \\A - Matches beginning of string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM