To create a map with initial key-value pairs in Ruby, you can use the hash literal syntax. This creates a new hash object with predefined key-value pairs.
We can create a map in Ruby with initial key-value pairs using the hash literal syntax, which initializes a map with predefined key-value pairs.
For example,
my_map
. This variable will hold our map with initial key-value pairs.my_map
variable. In this example, the map has string keys and integer values.my_map = {
'one' => 1,
'two' => 2,
'three' => 3
}
# Operations on the map
my_map.each do |key, value|
puts "#{key}: #{value}"
end
one: 1 two: 2 three: 3
We can create a map in Ruby with initial key-value pairs of different types using the hash literal syntax.
For example,
student_grades
. This variable will hold our map with initial key-value pairs where keys are strings (student names) and values are characters (grades).student_grades
variable. In this example, the map has string keys and string values representing grades.student_grades = {
'Alice' => 'A',
'Bob' => 'B',
'Charlie' => 'C'
}
# Operations on the map
student_grades.each do |key, value|
puts "#{key}: #{value}"
end
Alice: A Bob: B Charlie: C
We can create a map in Ruby with initial key-value pairs where keys are integers and values are floats using the hash literal syntax.
For example,
product_prices
. This variable will hold our map with initial key-value pairs where keys are integers (product IDs) and values are floats (prices).product_prices
variable. In this example, the map has integer keys and float values.product_prices = {
101 => 29.99,
102 => 39.99,
103 => 49.99
}
# Operations on the map
product_prices.each do |key, value|
puts "Product #{key}: $#{value}"
end
Product 101: $29.99 Product 102: $39.99 Product 103: $49.99
In this tutorial, we learned How to create a Map with Initial Key-Value Pairs in Ruby language with well detailed examples.