Sobes.tech
Junior

What is the key in an array and in a hash?

sobes.tech AI

Answer from AI

In an array, the key is the integer index of the element, starting from 0.

In a hash, the key is an object used to access the associated value. This can be any hashable object, such as a string, symbol, or number.

# Example array
arr = [10, 20, 30]
# Key 0 corresponds to value 10
# Key 1 corresponds to value 20
# Key 2 corresponds to value 30

# Example hash
hash = { "apple" => 1, :banana => 2, 3 => "cherry" }
# Key "apple" corresponds to value 1
# Key :banana corresponds to value 2
# Key 3 corresponds to value "cherry"