Search code examples
rubyarrayssplitcapitalize

Count capitalized of each sentence in a paragraph Ruby


I answered my own question. Forgot to initialize count = 0

I have a bunch of sentences in a paragraph.

  1. a = "Hello there. this is the best class. but does not offer anything." as an example.
  2. To figure out if the first letter is capitalized, my thought is to .split the string so that a_sentence = a.split(".")
  3. I know I can "hello world".capitalize! so that if it was nil it means to me that it was already capitalized EDIT
  4. Now I can use array method to go through value and use '.capitalize!
  5. And I know I can check if something is .strip.capitalize!.nil?

But I can't seem to output how many were capitalized.

EDIT

 a_sentence.each do |sentence|
        if (sentence.strip.capitalize!.nil?)
            count += 1
            puts "#{count} capitalized"
        end
    end

It outputs:

1 capitalized

Thanks for all your help. I'll stick with the above code I can understand within the framework I only know in Ruby. :)


Solution

  • Try this:

    b = []
    a.split(".").each do |sentence|
      b << sentence.strip.capitalize
    end
    b = b.join(". ") + "."
    #  => "Hello there. This is the best class. But does not offer anything."