Ruby 数一数单词中的字母
我想数一数字符串中的小写字母。假设我有:Ruby 数一数单词中的字母,ruby,string,Ruby,String,我想数一数字符串中的小写字母。假设我有: a = "SaMarMiShrA" 我知道a.count(“a-z”)会给出答案。但是如果没有内置的方法,如何不使用它呢 那么 应返回6,因为在“SaMarMiShrA”中,小写字母的数量是6。请对此提出解决方案。使用: 其他方式: => "SaMarMiShrA".chars.find_all { |x| /[[:lower:]]/.match(x) }.count #> 6 你可以这样做: def lower_case(string)
a = "SaMarMiShrA"
我知道a.count(“a-z”)会给出答案。但是如果没有内置的方法,如何不使用它呢
那么
应返回6
,因为在“SaMarMiShrA”
中,小写字母的数量是6。请对此提出解决方案。使用:
其他方式:
=> "SaMarMiShrA".chars.find_all { |x| /[[:lower:]]/.match(x) }.count
#> 6
你可以这样做:
def lower_case(string)
count = 0
string.split(//).each do |char|
if char == char.downcase
count += 1
end
end
return count
end
puts lower_case("AAAaaa")
=> 3
既然你想做“任何事”。数一数小写字母,你就得用猴子来修补字符串
class String
def count_small_letters
#any of @Зелёный suggestions or
scan(/[a-z]/).count
end
end
然后:
这听起来像是一个家庭作业问题。我不喜欢家庭作业问题。你能展示你到目前为止所做的尝试,提供一个无效的解决方案等吗?我试着这样做a。每个字节做c,把c放在末尾。它将给出assci代码,小写字母ASCII小于或等于65,并尝试计数它们。它不起作用。当你在计算
“SaMarMiShrA”
中的相关字母时,为什么要提到“SaMarMiShrA”
中的计数?@SamarKrMishra我认为我有权利(和责任)对我认为对他人有明确帮助的问题进行投票;还有我认为不是的否决票问题。你问了一个问题,但没有表现出任何解决问题的努力,所以我投了反对票。我的意思不是针对个人,我鼓励你继续问更多的问题(并提供更清晰的例子说明你已经尝试过的!),以便在将来问更多有用的问题,但在我看来,“如果不想更好地远离”并不是StackOverflow的工作方式。使用计数,避免另一种方式;)
def lower_case(string)
count = 0
string.split(//).each do |char|
if char == char.downcase
count += 1
end
end
return count
end
puts lower_case("AAAaaa")
=> 3
class String
def count_small_letters
#any of @Зелёный suggestions or
scan(/[a-z]/).count
end
end
> " SaMarMiShrA".count_small_letters
> 6