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
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]?


1 Answer 1

  1. 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.

  2. 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.

  • \$\begingroup\$ thanks, but it's still unclear for me how can we use accumulator in the case different from working with a Fixnum object? \$\endgroup\$
    – mac-r
    Mar 13, 2012 at 20:33
  • \$\begingroup\$ this is a good blog post about inject. \$\endgroup\$ Mar 13, 2012 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.