ruby hash loop

To loop over a Ruby hash, you can use the .each method along with a block. Here is an example:

hash = { "a" => 1, "b" => 2, "c" => 3 }

hash.each do |key, value|
  puts "Key: #{key}, Value: #{value}"
end

Explanation:

  1. We define a hash with three key-value pairs: { "a" => 1, "b" => 2, "c" => 3 }.
  2. We use the .each method to iterate over each key-value pair in the hash.
  3. Inside the block, we define two block variables: key and value. These variables will hold the current key and value from each iteration.
  4. We use puts to print the key and value for each iteration. The #{} syntax is used to interpolate the values of the variables within the string.
  5. The loop continues until all key-value pairs in the hash have been processed.

This code will output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

Please let me know if you have any further questions.