find the keys of a map in ruby

To get the keys of a Ruby hash (also called a map), you can use the keys method. Here's an example:

main.rb
my_map = { "a" => 1, "b" => 2, "c" => 3 }
keys = my_map.keys
puts keys.inspect
79 chars
4 lines

Output:

main.rb
["a", "b", "c"]
16 chars
2 lines

In this example, we create a hash called my_map with three key-value pairs. We then call the keys method on my_map to get an array of the keys, and assign it to a variable called keys. Finally, we use inspect to print the contents of the keys array.

The keys method returns an array of the keys in the order they were inserted into the hash. If you need them in a different order, you can use the sort, sort_by, or reverse methods on the array.

related categories

gistlibby LogSnag