Symbols Notes Day 1 Flashcards
what is a symbol?
a symbol is a data type similar to strings
what is the difference between a symbol and a string?
The most apparent difference between strings and symbols is that strings are mutable, while symbols are immutable
how do you denote a symbol?
using a colon
sym = :hello
sym[0] = “x”
p sym # => :hello
what is object_id and how do you find it?
object_id method. This will return the memory address of some data
why are symbols useful?
If we don't intend to mutate the string, we can use a symbol to save some memory. A symbol value will be stored in exactly one memory location: "hello".object_id # => 70233443667980 "hello".object_id # => 70233443606440 \:hello.object_id # => 2899228 \:hello.object_id # => 2899228
how do you use symbols as hash keys?
When initializing a hash with symbol keys, Ruby offers a shortcut. We can drop the rocket (=>) and move the colon (:) to the right of the symbol:
my_bootcamp = { name:”App Academy”, color:”red”, locations:[“NY”, “SF”, “ONLINE”] }
p my_bootcamp # => {:name=>”App Academy”, :color=>”red”, :locations=>[“NY”, “SF”, “ONLINE”]}
p my_bootcamp[:color] #=> “red