Search code examples
rubyarrayshashcountoperation

Ruby += operation throws error


I have a Hash and all values are arrays. So it looks like the following:

my_hash = {:key       => ["some string", "some string"],
           :other_key => ["some string"]}

Now i want the count of all strings in this hash.

So i do:

my_hash.each_value do |value|
  string_count += value.count
end

But I get the Error: undefined method '+' for nil:NilClass

But my value array is never nil... For example when I do:

my_hash.each_value do |value|
  puts value.count
end

I get:

2
1
2
2
2
etc.

So what am I doing wrong? Thx in Advance :)


Solution

  • I think you need to initialize string_count before loop.

    string_count = 0
    my_hash.each_value do |value|
      string_count += value.count
    end