ruby map hash
# Creating a hash with keys as integers and values as strings
original_hash = { 1 => 'one', 2 => 'two', 3 => 'three' }
# Using map on the hash to transform its keys and values
transformed_hash = original_hash.map do |key, value|
new_key = key * 2 # Doubling each key
new_value = value.upcase # Converting each value to uppercase
[new_key, new_value] # Creating an array with the new key-value pair
end.to_h # Converting the resulting array back to a hash
puts transformed_hash.inspect
Explanation:
1. original_hash
is a hash created with keys as integers and values as strings.
2. map
iterates through each key-value pair in original_hash
.
3. Inside the block, key * 2
doubles each key, storing the result in new_key
.
4. value.upcase
converts each value to uppercase and stores it in new_value
.
5. [new_key, new_value]
creates an array containing the new key-value pair.
6. The map
method returns an array of modified key-value pairs.
7. .to_h
converts the resulting array back into a hash.
8. transformed_hash
contains the modified hash with doubled keys and uppercase values.
9. puts transformed_hash.inspect
prints the modified hash to the console.