From: Brandon Weaver Date: 2013-01-29T02:56:03+09:00 Subject: Re: Please explain in English --20cf307d06785924ff04d45cfdca Content-Type: text/plain; charset=ISO-8859-1 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" 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/. > > --20cf307d06785924ff04d45cfdca Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable

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

Down case isn't necessary. The word count would be the same either w= ay.

Now if you just want to count words you don't even need that hash. I= f you're trying to count instances of words that's a different stor= y.

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&quo= t; <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<= br> that takes string and count words to return a Hash.

def count_words(string)
=A0 res =3D Hash.new(0)
=A0 string.downcase.scan(/\w+/).map{|word| res[word] =3D
string.downcase.scan(/\b#{word}\b/).size}
=A0 return res
end

--
Posted via http://= www.ruby-forum.com/.

--20cf307d06785924ff04d45cfdca--