Ömer Ömer - 2 months ago 6
Ruby Question

Printing hash contents with a line counter in Ruby

first of all let me tell you that I've searched Google, StackOverflow and even books like the Ruby Cookbook, etc. and still I couldn't find any solution for this simple problem:

myhash = Hash.new 0

myhash["wood"] = "any string"
myhash["palm"] = "any other string"
myhash["pine"] = "any thing"

myhash.each do |key, value|
puts "#{key}: #{value}"

I'd like to have an output like this:

1- wood: any string
2- palm: any other string
3- pine: any thing

i.e. a number (which I call "line counter") must be at the beginning of each line . I don't know how to add it into the iteration, how can I do it? Note: That must be done without using any gems. Thanks.


You can use each_with_index for this. However, you need to be sure and designate the key and value into a group with parentheses.

myhash.each_with_index do |(key, value), index|   # <-- Notice the group of (key, val)
  puts "#{index} - #{key}: #{value}"

For contrast, a normal array would use the method simply as

array.each_with_index do |val, index|