iterate over each key value in hash ruby
You can iterate over each key value in a hash in Ruby using the each
method. Here's an example:
hash = { a: 1, b: 2, c: 3 }
hash.each do |key, value|
puts "Key: #{key}, Value: #{value}"
end
In this example, we have a hash with keys :a
, :b
, and :c
, each associated with a value. We use the each
method to iterate over the hash, and for each key-value pair, the block of code inside the do...end
is executed. Inside the block, we use the variables key
and value
to access the key and value of each pair, and then we print them out using puts
. This will output the key-value pairs of the hash.