find the value associated with a key in a map in ruby

To find the value associated with a key in a Hash (or Map, as it is sometimes known), you can use the square bracket notation with the key as the argument. For example:

main.rb
my_map = { "a" => 1, "b" => 2, "c" => 3 }
value = my_map["b"]
puts value # output: 2
85 chars
4 lines

In this example, we create a Hash called my_map with three key-value pairs. We then retrieve the value associated with the key "b" by passing "b" as the argument to the [] method. The resulting value (2) is stored in the value variable, which we then print to the console.

related categories

gistlibby LogSnag