字符串#count选项

Nic*_*ilt 47 ruby string

从我理解第一个例子的文档String#count,但我不理解其余的例子:

a = "hello world"
a.count "lo"            #=> 5
a.count "lo", "o"       #=> 2
a.count "hello", "^l"   #=> 4
a.count "ej-m"          #=> 4
Run Code Online (Sandbox Code Playgroud)

任何解释都会有所帮助.

Jon*_*ern 74

这是最愚蠢的ruby方法之一,并且引导相当糟糕的文档.扔了一圈.我最终看着它,因为它看起来应该给我一个给定字符串出现次数.不.不是远程关闭.但这是我最终计算字符串出现的方式:

s="this is a string with is thrice"
s.scan(/is/).count  # => 3
Run Code Online (Sandbox Code Playgroud)

让我想知道为什么有人要求这种方法,以及为什么文档是如此糟糕.几乎就像记录代码的人真的没有关于要求这个功能的人类可理解的"商业"理由的线索.

count([other_str]+) ? fixnum

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


edm*_*dmz 36

如果您将多个参数传递给count,它将使用这些字符串的交集并将其用作搜索目标:

a = "hello world"
a.count "lo"            #=> finds 5 instances of either "l" or "o"
a.count "lo", "o"       #=> the intersection of "lo" and "o" is "o", so it finds 2 instances
a.count "hello", "^l"   #=> the intersection of "hello" and "everything that is not "l" finds 4 instances of either "h", "e" or "o"
a.count "ej-m"          #=> finds 4 instances of "e", "j", "k", "l" or "m" (the "j-m" part)
Run Code Online (Sandbox Code Playgroud)


FMc*_*FMc 10

每个参数定义一组字符.这些集合的交集确定count用于计算计数的整体集合.

a = "hello world"

a.count "lo"            # l o       => 5
a.count "lo", "o"       # o         => 2
Run Code Online (Sandbox Code Playgroud)

并且^可以(在所有字母用于否定hello,除l)

a.count "hello", "^l"   # h e o     => 4
Run Code Online (Sandbox Code Playgroud)

范围可以定义为-:

a.count "ej-m"          # e j k l m => 4
Run Code Online (Sandbox Code Playgroud)


Rus*_*Cam 10

让我们打破这些

a = "hello world"
Run Code Online (Sandbox Code Playgroud)
  1. 计算字母的出现次数lo

    a.count "lo" #=> 5

  2. 找到的交叉loo(其正在计数的出现次数lo,并采取只有计数的o从出现):

    a.count "lo", "o" #=> 2

  3. 计数的发生次数h,e,l,lo,然后用任何相交不在l(其产生相同的结果寻找的出现h,eo)

    a.count "hello", "^l" #=> 4

  4. 计数的发生次数e之间的任何字母jm(j,k,lm):

    a.count "ej-m" #=> 4


小智 5

在字符串中使用 gsub

a = "hello world hello hello hello hello world world world"
2.1.5 :195 > a.gsub('hello').count
=> 5 
Run Code Online (Sandbox Code Playgroud)


Pet*_*ete 2

我来一击:

第二个示例:使用措辞“这些集合的交集定义了要在 str 中计数的字符”,参数是“lo”和“o”。这些的交集就是“o”,其中在被计数的字符串中有 2 个。因此返回值为 2。

第三个例子:这个似乎是在说:“‘hello’中的任何字符,但不是字符‘l’”。从“以插入符号 (^) 开头的任何 other_str 被否定”这一行得到这一点。因此,您可以计算字符串“hello”中包含的字母集,这些字母在“hello world”中找到(即h,e,l,l,o,o,l),然后将交集与"^l"(即h,e,o,w,o,r,d)你剩下4(即h,e,o,o)。

第四个例子:这个基本上是说“计算所有‘e’字符以及‘j’和‘m’之间的任何字符。‘j’和‘m’之间包含一个‘e’和3个字符,并且所有3个字符恰好是是字母“l”,这又让我们得到答案 4。