ruby hash print
person = { name: "John", age: 30, city: "New York" }
person.each do |key, value|
puts "#{key}: #{value}"
end
Explanation:
1. A hash named person
is created with key-value pairs. Keys are symbols (name
, age
, city
) and values are associated with each key ("John"
, 30
, "New York"
).
2. The each
method is used to iterate through each key-value pair in the person
hash.
3. Within the do..end
block, |key, value|
is used to represent the key and value of each pair during iteration.
4. puts "#{key}: #{value}"
prints each key-value pair in the format key: value
using string interpolation. This displays the content of the hash on separate lines.