Regex is critical to this one. \w is word boundary. Scan returns everything
that matches that regex with a boolean true.

Down case isn't necessary. The word count would be the same either way.

Now if you just want to count words you don't even need that hash. If
you're trying to count instances of words that's a different story.

Suggested reading: Enumerables, Blocks, Scan, Inject, and Reduce.

Enumerable covers most of those. Read the Ruby docs.

Seeing as I'm on my phone at the moment, could someone else rewrote that
code a bit? It'd look all types of funky if I did right now.

Cheers.
On Jan 28, 2013 11:40 AM, "jooma lavata" <lists / ruby-forum.com> wrote:

> I'm learning Ruby and I'm reading some expression that I saw on the
> forum. I'm coming from Javascript. This is really hard for me. Please
> help explain to me in plain English. I understand that it's a Function
> that takes string and count words to return a Hash.
>
> def count_words(string)
>   res = Hash.new(0)
>   string.downcase.scan(/\w+/).map{|word| res[word] =
> string.downcase.scan(/\b#{word}\b/).size}
>   return res
> end
>
> --
> Posted via http://www.ruby-forum.com/.
>
>