2015-08-17 189 views
-3

我想計算字符串中存在的小寫字母。假設我有:用單詞計算字母

a = "SaMarMiShrA" 

我知道a.count(「a-z」)會給出答案。但如何在沒有內置方法的情況下使用此功能。

而且,由於在"SaMarMiShrA"

def count_small_letters 
    #code 
end 
a.count_small_letters 

應該返回6,小字母字母的數量爲6,請提出一個解決方案。

+2

這聽起來像一個家庭作業的問題。我不喜歡家庭作業問題。你可以展示你到目前爲止所嘗試過的,提供非工作解決方案等嗎? –

+0

我試過這樣做a.each_byte do | c | 把c 結束 得到 –

+0

它會給assci代碼和小寫字母ASCII小於65或相等,並嘗試數它們。它沒有奏效。 –

回答

2

既然你希望能夠做 「什麼」。 count_small_letters你將不得不猴子補丁字符串,所以

class String 
    def count_small_letters 
    #any of @Зелёный suggestions or 
    scan(/[a-z]/).count 
    end 
end 

然後:

> " SaMarMiShrA".count_small_letters 
> 6 
5

使用count

=> "SaMarMiShrA".count("a-z") 
#> 6 
=> "SaMarMiShrA".count("A-Z") 
#> 5 

其他方式:

=> "SaMarMiShrA".chars.find_all { |x| /[[:lower:]]/.match(x) }.count 
#> 6 
+0

使用'count',避開其他方式;) – Stefan

1

你可以這樣做:

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