问题描述
我很难理解 Ruby 文档:
a = "hello world"
a.count "lo" #=> 5
a.count "lo", "o" #=> 2
a.count "hello", "^l" #=> 4
a.count "ej-m" #=> 4
"hello^world".count "\\^aeiou" #=> 4
"hello-world".count "a\\-eo" #=> 4
尤其是这段代码a.count "ej-m"
.谁能解释一下它是如何工作的?
especially this code a.count "ej-m"
. Can anyone please explain how it works?
推荐答案
想象一下由正则表达式语法中的 [
和 ]
包裹的模式"字符串,它们是匹配每个字符.
Just imagine the "pattern" strings as wrapped by [
and ]
from regex syntax, that are matched against each character.
所以,如果我们将 a = "hello world"
分解成字符:
So, if we break a = "hello world"
into characters:
[1] pry(main)> a = "hello world"
=> "hello world"
[2] pry(main)> a.split('')
=> ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
并将ej-m"转换为用 [
和 ]
包裹的正则表达式,我们得到 /[ej-m]/
- 这意味着'e'
或从 'j'
到 'm'
的任何字符(包括两者):
And convert "ej-m" to regex wrapped with [
and ]
we get /[ej-m]/
- which means either 'e'
or any character from 'j'
to 'm'
(including both):
[3] pry(main)> a.split('').select{|c| c=~ /[ej-m]/}
=> ["e", "l", "l", "l"]
我们有 4 场比赛 - 这也是您得到的结果.本质上 a.count "ej-m"
等价于:
We got 4 matches - which is also the result you get. Essensially a.count "ej-m"
is equivalent to:
[4] pry(main)> a.split('').count{|c| c=~ /[ej-m]/}
=> 4
方法的多个参数只是匹配之间的和
:
Multiple arguments to the method are just and
between the matches:
[5] pry(main)> a.split('').count{|c| c =~ /[hello]/ and c =~ /[^l]/}
=> 4
这篇关于Ruby 中的 count 方法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!