modzking4
modzking4

Reputation: 143

im having an issue with my code counting occurring characters

I'm creating a Ruby program that will use "hello world!" as a standard string unless a string is specified, I can get it to register the "hello world" or any string I pass in through IRB but once I get to the calculation method I'm getting method errors and don't know where it's going wrong.

def display
  calculateFrequencies
end
private
def calculateFrequencies
  @text = "Hello World!"
  @letters = text.downcase.each_char.with_object(Hash.new(0)) do |c, letters|
      next if c == " "
      @letters[c] += 1
  end
end

the expected output would be for example it calculates the frequency and then when the method display is called then the frequency will be shown in the terminal e.g. Hello World = h=1 e=2 l=3 o=2 d=1 but what I am actually getting is this.

h.calculateFrequencies
NoMethodError: undefined method `[]' for nil:NilClass
from LetterHistogram.rb:17:in `block in calculateFrequencies'
from LetterHistogram.rb:15:in `each_char'
from LetterHistogram.rb:15:in `with_object'
from LetterHistogram.rb:15:in `calculateFrequencies'
from (irb):5
from /usr/bin/irb:11:in `<main>'

Upvotes: 2

Views: 58

Answers (1)

mrzasa
mrzasa

Reputation: 23317

Inside the block you're trying to use a non-initialized instance variable @letters as it were an initialized hash/array. You either need to initialize it before you call the block or (rather) use the block param. I'd suggest to try sth like this:

def calculateFrequencies
  @text = "Hello World!"
  @letters = @text.downcase.each_char.with_object(Hash.new(0)) do |c, letters|
      next if c == " "
      letters[c] += 1
  end
end

It works in my console:

[8] pry(main)> @text = "Hello World!"  
=> "Hello World!"
[9] pry(main)> @letters = @text.downcase.each_char.with_object(Hash.new(0)) do |c, letters|  
[9] pry(main)*   next if c == " "      
[9] pry(main)*   letters[c] += 1      
[9] pry(main)* end    
=> {"h"=>1, "e"=>1, "l"=>3, "o"=>2, "w"=>1, "r"=>1, "d"=>1, "!"=>1}

Upvotes: 2

Related Questions