2011-03-14 68 views

回答

2

我要一刺:

第二个例子:使用的措辞“这些集合的交集定义了字符在STR数”的参数是“LO”和“o”。这些交点只是其中有2个字符串被计入的“o”。因此返回值为2.

第三个例子:这个人似乎在说:“'hello'中的任何字符,而不是'l'字符。从行中获取“任何以插入符号(^)开头的other_str都是否定的”。因此,您可以计算在“hello world”(即h,e,l,l,o,o,l)中找到的字符串“hello”中包含的字母集合,然后将交集与"^l"(即h,e,o,w,o,r,d)你留下4(即h,e,o,o)。第四个例子:这个基本上说“统计所有'e'字符和'j'和'm'之间的任何字符。'j'和'm'之间有一个'e'和3个字符,以及所有3个恰好是字母'l',我们再次回答4。

+0

可以解释这个“你可以计算字符串中包含的所有字母”你好“(有7个)”更好,所以我可以投票给你吗?谢谢:) – 2016-06-03 06:29:05

32

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

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) 
+0

ouptput的a.count(' e-r')变成8. – sunil 2014-11-25 15:06:25

+1

@sunil a.count('e-r')匹配“helloorl”,因此8. – 2014-11-28 09:35:18

8

每个参数定义了一组字符的相交的那些集的决定了整体。设置count用来计算一个计数。

a = "hello world" 

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

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

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

范围可以与-定义:

a.count "ej-m"   # e j k l m => 4 
10

让我们打破这些下来

a = "hello world" 
  1. 算字母l的出现的次数和o

    a.count "lo" #=> 5

  2. 找到loo相交(这是计数的lo和服用发生的次数仅发生次数为o):

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

  3. 计数的hello出现的次数,然后用任何不属于l(其产生相同的结果到的heo发现出现)

    相交

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

  4. 来算的e出现的次数和j和之间的任何字母(jklm):

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

59

这是的dorkiest红宝石的方法之一,并且非常糟糕的文档进行引导。扔我一个循环。我最终看着它,因为它看起来应该给我一个给定字符串的出现次数。不。不是很近。但这里是我是如何结束计数字符串出现:

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

使我不知道为什么有人问这个方法,为什么文档是如此糟糕。几乎就像记录代码的人真的不知道要求这个功能的人可以理解的“业务”原因。

count([other_str]+) → fixnum

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

+0

嗯,我想如果你想计算一个特定字符的数量,或者一组的特定*字符*,你宁愿使用一个可能优化的方法 'header =“foo,bar,baz,foo,bar,baz2,foo,bar,baz,foo,bar,baz3” Benchmark.bm do | [R | r.report(“使用字符串#扫描”){100000.times {header.scan(/,使用字符串#计数){100000.times {header.count(',')}} r.report /).count}} 结束' 结果在String#count - > 0.014870,String#scan 0.467562' – radiospiel 2017-05-17 09:58:50