DEV Community

Jewell Borders
Jewell Borders

Posted on

Today I Learned 2/11/23

In Ruby, symbols are immutable and primarily used as hash keys or for referencing method names.
Immutable means they are can't be changed once set.

Image description

item[:name] = "Bread"

and then 

item["name"] = "Bread"

From the two above example, I can change the hash value of the second example as much as I like, but not the first.

Another helpful tip my instructor Robert told me was:

If a symbol is not already in the hash, then we can only use it to set a new value.

h={}
p h # nothing in there yet
h[:x]=5
h["x"]=4
p h # print the entire hash
p h[:x]
p h["x"]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)