Programming Ruby 3.2: Ruby Hash#each erroneous example

@noelrappin

In the section of Chapter 4 that discusses the Hash class / data structure and iteration over hashes, under the subheading Blocks and Enumeration, the example given is of the form myHash.each { |index| ...}. Specifically, it’s:

top_five.each do |i|
  word = top_five[i][0]
  count = top_five[i][1]
  puts "#{word}: #{count}"
end

… which doesn’t work, because each passes each key-value pair as an array to the block in that case, not an index.

The example is also not the code previously encountered, as alleged, which was:

top_five.reverse_each do |word, count|
  puts "#{word}: #{count}"
end

As a Ruby nuby, I had to investigate and demonstrate to myself what the each method pases to a block that takes a single parameter. At first, I thought it would pass key alone, but no, it’s [key, value]. Good to know. Maybe that should be mentioned explicitly. If the book contained exercises (I haven’t seen any yet), it would be a good exercise for the reader to go to replit.com or irb etc. and find out, given that I don’t recall the point having been made prior to the mentioned subheading.

I imagine this is what was intended, fwiw:

top_five.each_pair do |pair|
  word = pair[0]
  count = pair[1]
  puts "#{word}: #{count}"
end

It works, but obviously can be rendered more elegant.

Thanks – that’s a very good catch – the code was updated in the sample in the previous section but the text of this section (which is mostly using this code to present each) wasn’t updated to match. The code snippet displayed is from the previous version and doesn’t match the discussion, we’ll update the text to make everything line up!

Thanks,

Noel