简体   繁体   中英

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}"
end

I'd like to have an output like this:

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

ie 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}"
end

The reason you're required to group the key and value in parentheses is because the each_with_index method takes only produces variables to the block loop; normally the value and index . Therefore, you need to deconstruct the first element (key and value) explicitly.

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

array.each_with_index do |val, index|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM