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]?
1 Answer 1
It is about
inject
initial value when you giveHash.new(0)
and callc[w] += 1
in block it is expanded toc[w] = c[w] + 1
as we said toHash
initializer if it has no key then key will set to0
when first appeared.c
here is an accumulator and instance ofinject
initial value. accumulator value will be set to return value of the block after every turn. we are returningc
because of this. it can be type of any object.(1..10).inject(0) {|a,x| a + x }
for example it isFixnum
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– mac-r2012年03月13日 20:33:19 +00:00Commented Mar 13, 2012 at 20:33
-
\$\begingroup\$ this is a good blog post about
inject
. \$\endgroup\$Selman Ulug– Selman Ulug2012年03月13日 20:36:57 +00:00Commented Mar 13, 2012 at 20:36