Sobes.tech
Junior

What do square brackets in a hash signify?

sobes.tech AI

Answer from AI

Square brackets ([]) in Ruby hashes are used to access the value by key or to set/update (assign) a value for a specific key.

Accessing a value:

# Creating a hash
my_hash = { "key1" => "value1", "key2" => "value2" }

# Accessing a value by key
value = my_hash["key1"] 
# value now contains "value1"

Setting/updating a value:

# Creating a hash
my_hash = { "key1" => "value1" }

# Setting a new value for an existing key
my_hash["key1"] = "new_value1" 
# my_hash now is {"key1"=>"new_value1"}

# Adding a new key and value
my_hash["new_key"] = "new_value"
# my_hash now is {"key1"=>"new_value1", "new_key"=>"new_value"}

In fact, [] in hashes is a method defined for the Hash class, which is overloaded to perform both of these operations.