ruby count 函数的一个用法,不知道是什么意思
黄舟
黄舟 2017-04-24 09:13:15
0
1
873

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

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

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

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. 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"                   #=> 5
a.count "lo", "o"              #=> 2
a.count "hello", "^l"          #=> 4
a.count "ej-m"                 #=> 4

"hello^world".count "\\^aeiou" #=> 4
"hello-world".count "a\\-eo"   #=> 4

c = "hello world\\r\\n"
c.count "\\"                   #=> 2
c.count "\\A"                  #=> 0
c.count "X-\\w"                #=> 3
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
阿神

Each parameter represents a set, ^表示补集 ("^l" represents except l). Returns the number of characters in a within the range of (the intersection of all parameters).

The intersection of the set "hello" and the set "^l" is "heo", so we count 4

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!