What to do = ~ and / \ mean in Ruby?

I taught myself Ruby for a specific problem that I am trying to solve. I notice that many people are using =~, and /\in your code. I'm not quite sure how they work, and just wanted to explain. For example, I looked at someones code for this Pig Latin translator, and this is the first time I see them 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 just got confused about the features /\and=~

+4
source share
4 answers

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

/\ . / , \A "" " ".

edit: , , .

'/\'

+23

=~ Ruby.

.

, . , nil.

/abc/ =~ "abcdef"

0, "abc" .

/xyz/ =~ "abcdef"

nil, "xyz" .

/\:

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

:

\d => Matches all digits
+6

Ruby "match". , . :

/or/ =~ "Hello World"

7, 7 . 0.

:

/abc/ =~ "Hello World"

nil, .

0

/\A =~ , , . Ruby:

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"

^ , \A, "...". :

  • ^ -
  • \A - .
0

All Articles