字符串#count 选项 [英] String#count options

查看:39
本文介绍了字符串#count 选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 String#count 我理解第一个例子,但我不理解其余的例子:

From the documentation for String#count I understand the first example, but I do not understand the rest of the examples:

a = "hello world"
a.count "lo"            #=> 5
a.count "lo", "o"       #=> 2
a.count "hello", "^l"   #=> 4
a.count "ej-m"          #=> 4

任何解释都会有所帮助.

Any explanation will be helpful.

推荐答案

这是最笨拙的 ruby​​ 方法之一,而且启动文档非常糟糕.把我扔了一个循环.我最终查看了它,因为它看起来应该给我一个给定字符串的出现次数.不.不是远程关闭.但这是我最终计算字符串出现次数的方式:

This is one of the dorkiest ruby methods, and pretty lousy documentation to boot. Threw me for a loop. I ended up looking at it because it looked like it should give me the count of occurrences of a given string. Nope. Not remotely close. But here is how I ended up counting string occurrences:

s="this is a string with is thrice"
s.scan(/is/).count  # => 3

让我想知道为什么有人要求使用这种方法,以及为什么文档如此糟糕.几乎就像编写代码的人真的不知道要求此功能的人类可以理解的业务"原因一样.

Makes me wonder why someone asked for this method, and why the documentation is so lousy. Almost like the person documenting the code really did not have a clue as to the human-understandable "business" reason for asking for this feature.

count([other_str]+) → fixnum

每个 _other_str_ 参数定义一组要计数的字符.这这些集合的交集定义了要在 str 中计数的字符.任何以插入符号 (^) 开头的 _other_str_ 被否定.序列 c1–c2表示 c1c2 之间的所有字符.

Each _other_str_ parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any _other_str_ that starts with a caret (^) is negated. The sequence c1–c2 means all characters between c1 and c2.

这篇关于字符串#count 选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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