# Programming Ruby 3.2: Ruby Hash#each erroneous example

**URL:** <https://forum.devtalk.com/t/programming-ruby-3-2-ruby-hash-each-erroneous-example/85974>\
**Category:** PragProg Customers\
**Tags:** block, ruby, argument, hash, each\
**Created:** [7 December 2022 01:14 UTC](https://forum.devtalk.com/t/programming-ruby-3-2-ruby-hash-each-erroneous-example/85974 "2022-12-07T01:14:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ghenry74](https://forum.devtalk.com/user_avatar/forum.devtalk.com/ghenry74/32/4671_2.png) [@ghenry74](https://forum.devtalk.com/u/ghenry74)\
**Post date:** [7 December 2022 01:14 UTC](https://forum.devtalk.com/t/programming-ruby-3-2-ruby-hash-each-erroneous-example/85974/1 "2022-12-07T01:14:22Z")

</div>

@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:

```auto
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:

```auto
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](http://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:

```auto
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.

---

<div class="post-metadata">

**Author:** ![noelrappin](https://forum.devtalk.com/user_avatar/forum.devtalk.com/noelrappin/32/481_2.png) [@noelrappin](https://forum.devtalk.com/u/noelrappin)\
**Post date:** [8 December 2022 02:26 UTC](https://forum.devtalk.com/t/programming-ruby-3-2-ruby-hash-each-erroneous-example/85974/2 "2022-12-08T02:26:31Z")

</div>

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
