问题描述
我一直在自学 Ruby,对于我试图解决的某个问题,我注意到很多人在他们的代码中使用 =~
和 /\
代码.我不太确定它们是如何工作的,只是想要一个解释.例如,我正在查看这个 Pig Latin 翻译器的代码,这是我第一次看到这些代码被使用.
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
我只是对 /\
斜杠和 =~
推荐答案
=~
被称为匹配运算符",可用于将字符串与正则表达式进行匹配.
=~
is known as the "match operator" and can be used to match a string against a regular expression.
/\
实际上是两个独立事物的一部分./
表示正则表达式的开头,\A
被称为锚点",表示从字符串的开头匹配".
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."
感谢 Wayne Conrad 对/\"的更正
thank you to Wayne Conrad for a correction on '/\'
这篇关于=~ 和/\ 在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!