ruby count 函数的一个用法,不知道是什么意思

【字号: 日期:2022-10-15浏览:39作者:雯心

问题描述

帮忙解释一下如下代码含义:

a = 'hello world'a.count 'hello', '^l' #=> 4

以下是官方文档中的解释:http://ruby-doc.org/core-2.3.0/String.html#method-i-count

count([other_str]+) → fixnumEach 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. The backslash character can be used to escape ^ or - and is otherwise ignored unless it appears at the end of a sequence or the end of a other_str.

a = 'hello world'a.count 'lo' #=> 5a.count 'lo', 'o' #=> 2a.count 'hello', '^l' #=> 4a.count 'ej-m' #=> 4'hello^world'.count '^aeiou' #=> 4'hello-world'.count 'a-eo' #=> 4c = 'hello worldrn'c.count '' #=> 2c.count 'A' #=> 0c.count 'X-w'#=> 3

问题解答

回答1:

每个参数表示一个集合, ^表示补集 ('^l'表示除了l). 返回a中在(所有参数的交集)范围内的字符数.

集合'hello'和集合'^l'的交集是'heo', 所以数出来4个

相关文章: