Words counter with a hash My problem is the following: I wrote a method, which counts words and returns a hash. There is a Ruby idiom which was found by me in some of the forums discussions, which I don't understand.

Here is the whole code:

text = "bla bla blahh blahh"
def count_words(string)
  inp = string.downcase.scan(/\b[\'a-z]+\b/i).inject(Hash.new 0){|c,w| c[w]+=1;c }
  return inp
end
puts count_words(text)


Here is the idiom: inject(Hash.new 0){|c,w| c[w]+=1;c }

My concrete questions are the following:

1) How it understands when we should add 1 to the particular key?

2) As far as I understand "inject" method, "c" is some sort of counter. So how does it happen that we write c[w]?
It is about inject initial value when you give Hash.new(0)
and call c[w] += 1 in block it is expanded to c[w] = c[w] + 1 as we said
to Hash initializer if it has no key then key will set to 0 when
first appeared.
c here is an accumulator and instance of inject initial value.
accumulator value will be set to return value of the block after
every turn. we are returning c because of this. it can be type of
any object. (1..10).inject(0) {|a,x| a + x } for example it is
Fixnum here.