本文介绍了=~ 和/\ 在 Ruby 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在自学 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 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 08:19