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:
- We define a hash with three key-value pairs:
{ "a" => 1, "b" => 2, "c" => 3 }
. - We use the
.each
method to iterate over each key-value pair in the hash. - Inside the block, we define two block variables:
key
andvalue
. These variables will hold the current key and value from each iteration. - 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. - 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.