String#count options

前端 未结 6 671
Happy的楠姐
Happy的楠姐 2021-02-02 06:01

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\"              


        
6条回答
  •  执念已碎
    2021-02-02 06:12

    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

    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.

提交回复
热议问题