Hashes & Symbols Flashcards

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

What is a Hash?

A

A collection of key-value pairs. A key is like a unique variable that is assigned a value. Keys must be unique but values can be repeated/re-used.

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

How to set a default value (which will be returned if you try to access a non-existent key in a hash)

A

By using the Hash.new method and setting the default as a parameter/argument

hash_name = Hash.new(“default_value”)

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

What is a symbol?

A

A Symbol is the most basic Ruby object you can create. It’s just a name and an internal ID. Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.

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

.object_id method

A

returns the ID of an object

puts “string”.object_id => 6284180
puts “string”.object_id => 6283980

puts :symbol.object_id => 802268
puts :symbol.object_id => 802268

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

What are symbols primarily used for?

A

Hash keys and method names

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

Why do symbols make good hash keys?

A
  1. They’re immutable, meaning they can’t be changed once they’re created;
  2. Only one copy of any symbol exists at a given time, so they save memory;
  3. Symbol-as-keys are faster than strings-as-keys because of the above two reasons.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Methods used to convert a symbol to a string and vice versa

A

.to_sym

.to_s

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

Another way to convert a string to a symbol (other than .to_sym

A

.intern

This will internalize the string into a symbol and works just like .to_sym

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

Change to hash creation with Ruby 1.9

A

The two changes are:

  1. You put the colon at the end of the symbol, not at the beginning;
  2. You don’t need the hash rocket anymore.
new_hash = { 
  one: 1,
  two: 2,
  three: 3
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Methods to iterate over just keys or just values without having a custom block of code

A

.each_key AND .each_value

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

The Case Statement syntax

A
case language
  when "JS"
    puts "Websites!"
  when "Python"
    puts "Science!"
  when "Ruby"
    puts "Web apps!"
  else
    puts "I don't know!"
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly