Ruby 中的 count 方法是如何工作的? [英] How does count method works in Ruby?

查看:46
本文介绍了Ruby 中的 count 方法是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解 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 方法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆