Hashes & Symbols Flashcards
What is a Hash?
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 to set a default value (which will be returned if you try to access a non-existent key in a hash)
By using the Hash.new method and setting the default as a parameter/argument
hash_name = Hash.new(“default_value”)
What is a symbol?
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.
.object_id method
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
What are symbols primarily used for?
Hash keys and method names
Why do symbols make good hash keys?
- They’re immutable, meaning they can’t be changed once they’re created;
- Only one copy of any symbol exists at a given time, so they save memory;
- Symbol-as-keys are faster than strings-as-keys because of the above two reasons.
Methods used to convert a symbol to a string and vice versa
.to_sym
.to_s
Another way to convert a string to a symbol (other than .to_sym
.intern
This will internalize the string into a symbol and works just like .to_sym
Change to hash creation with Ruby 1.9
The two changes are:
- You put the colon at the end of the symbol, not at the beginning;
- You don’t need the hash rocket anymore.
new_hash = { one: 1, two: 2, three: 3 }
Methods to iterate over just keys or just values without having a custom block of code
.each_key AND .each_value
The Case Statement syntax
case language when "JS" puts "Websites!" when "Python" puts "Science!" when "Ruby" puts "Web apps!" else puts "I don't know!" end