Newbie ruby array question

Hi everyone,
I have this code from tryruby.
ratings = Hash.new(0)
books.values.each { |rate| ratings[rate] += 1 }

I was wondering if anyone can explain in plain english how ratings[rate]
is keeping count to be able to increase 1. In other languages to
increase 1 you need a variable to hold the count but how is it being
tallied up here? Can anyone help me I’m completely new with ruby. I
would be very grateful with any insight any of you gurus could pass on
to me.

Thank you,
sean.

Hash.new(0) creates a dictionary-type object with the default value of
0. Whatever “word” you search for, you get 0 back.

When you do “ratings[rate]” the first time for each book, you get a 0.
The zero then has 1 added to it and is put back into the Hash.

The second time that same book comes up, it returns a 1.
You then add another 1, making the Hash hold 2 for that book.

Rather than having a different variable for every book, you can now have
one variable that understands book names and can hold separate values
for each book.

Oh wow! Thanks Joel, You totally rock! Your explanation is right on
point! Just what I needed, couldn’t make sense of it before but now I
totally get it. Thanks so much.
Thank you,
sean.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs