Samar Kr Mishra Samar Kr Mishra - 2 months ago 7
Ruby Question

Count letters in a word

I want to count the small letter alphabets present in a string. Say I have:

a = "SaMarMiShrA"


I know that a.count("a-z") will give the answer. But how to do without using this without inbuilt methods.

Then,

def count_small_letters
#code
end
a.count_small_letters


should return
6
since in
"SaMarMiShrA"
, the number of small letter alphabets is 6. Please suggest a solution for this.

Answer

Since you want to be able to do "whatever".count_small_letters you would have to monkey patch String so

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

Then:

> " SaMarMiShrA".count_small_letters
> 6
Comments