Home > database >  Iterating over loops in ruby?
Iterating over loops in ruby?

Time:09-20

I am new to ruby. I am trying to create a letter counter. my intended output was supposed to be [2,"I"] but I keep getting [3,"D]. Any help in understanding where I went wrong would be so helpful, thank you.

class LetterCounter
      def initialize(text)
        @text = text
      end
    
      def calculate_most_common()
        counter = Hash.new(1)
        most_common = nil
        most_common_count = 1
        @text.chars.each do |char|
          next unless is_letter?(char)
          counter[char] = (counter[char] || 1)   1
          if counter[char] > most_common_count
            most_common = char
            most_common_count  = counter[char]
          end
        end
        return [most_common_count, most_common]
      end
    
      private
    
      def is_letter?(letter)
        return letter =~ /[a-z]/i
      end
    end
    
    counter = LetterCounter.new("Digital Punk")
    p counter.calculate_most_common

# Intended output:
# [2, "i"]

CodePudding user response:

Try:

class LetterCounter
    def initialize(text)
        @text = text
    end
    
    def calculate_most_common()
        [email protected](/[a-z]/i)
        arr.each_with_object(Hash.new(0)) { |n,h| h[n]  = 1 }.max_by(&:last)
    end
    
end
    
counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common

Prints:

["i", 2]

If you want to fix yours, try:

class LetterCounter
    def initialize(text)
        @text = text
    end
    
    def calculate_most_common()
        counter = Hash.new(0)
        most_common = nil
        most_common_count = 0
        @text.chars.each do |char|
            next unless is_letter?(char)
            counter[char]  = 1
            if counter[char]>most_common_count
                most_common=char 
                most_common_count=counter[char]
            end 
        end
        return [most_common_count, most_common]
    end
    
    private
    
    def is_letter?(letter)
        return letter =~ /[a-z]/i
    end
end

counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common

CodePudding user response:

class LetterCounter
  def initialize(text)
    @text = text
  end

  def calculate_most_common()
    counter = Hash.new(0)  # wrong initialization in your code
    most_common = nil
    most_common_count = 0
    @text.chars.each do |char|
      next unless is_letter?(char)
      counter[char] = (counter[char] || 1)   1
      puts "#{char} #{counter[char]}"
      if counter[char] > most_common_count
        puts "most common: #{most_common_count} #{char} #{counter[char]}"
        most_common = char
        most_common_count = counter[char] # error in your code
      end
    end
    return [most_common_count, most_common]
  end

  private

  def is_letter?(letter)
    return letter =~ /[a-z]/i
  end
end

counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common
  • Related