Symbols Notes Day 1 Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

what is a symbol?

A

a symbol is a data type similar to strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what is the difference between a symbol and a string?

A

The most apparent difference between strings and symbols is that strings are mutable, while symbols are immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

how do you denote a symbol?

A

using a colon
sym = :hello
sym[0] = “x”
p sym # => :hello

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what is object_id and how do you find it?

A

object_id method. This will return the memory address of some data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

why are symbols useful?

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how do you use symbols as hash keys?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly