2011-03-14 63 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