How to access results from one method into another

Viewed 23

I am new to ruby. I am a bit stuck on a class question. I am writing a grammar checker class method that first checks( check method) if the text given follows correct punctuation(starts with a capital letter and ends with a correct punctuation mark). In the percentage good method, I want to then use the correct texts from the check method and divide it by total texts inputted to get a percentage of how many texts are grammatically correct but I don't know how to access the results from the check method in the percentage good method? Any tips would be greatly appreciated

class GrammarStats
        
      def initialize
          @correct_texts= []
          @total_texts = []
        end
      
        def check(text) # text is a string
            @total_texts.push(text)
            fail "Give me a string" if !text.is_a? String or text == ""
            result = text.match?(/^[A-Z][\s\S]*?\+?[.?!](?:\n\n|$)/)
        end
    
        def percentage_good
           
          # Returns as an integer the percentage of texts checked so far that   passed
          # the check defined in the `check` method. The number 55 represents 55%.
    
          
        end
end
1 Answers

I may not have fully understood what you wanted.. But I think something like this? ;)

class GrammarStats
  def initialize
    @correct_texts = []
    @total_texts = []
  end

  def correct?(text)
    raise "Give me does not enpty string" unless text.is_a? String && text.present?

    @total_texts << text
    return false unless text.match?(/^[A-Z][\s\S]*?\+?[.?!](?:\n\n|$)/)
   
    @correct_texts << text
    true
  end

  def percentage_good
     retrun '0%' if @total_texts.blank?
    
     "#{((@correct_texts.count.to_f/@total_texts.count) * 100).round(2)}%"
  end
end
Related