计算单词中的字母

Sam*_*Sam -3 ruby string

我想计算字符串中存在的小写字母.说我有:

a = "SaMarMiShrA"
Run Code Online (Sandbox Code Playgroud)

我知道a.count("az")会给出答案.但是如果没有内置方法,不使用它就该怎么做.

然后,

def count_small_letters
  #code
end
a.count_small_letters
Run Code Online (Sandbox Code Playgroud)

应该返回,6因为"SaMarMiShrA",小写字母的数量是6.请为此建议一个解决方案.

Зел*_*ный 5

用途count:

=> "SaMarMiShrA".count("a-z")
#> 6
=> "SaMarMiShrA".count("A-Z")
#> 5
Run Code Online (Sandbox Code Playgroud)

另一种方式:

=> "SaMarMiShrA".chars.find_all { |x| /[[:lower:]]/.match(x) }.count
#> 6
Run Code Online (Sandbox Code Playgroud)