Ruby Intro - Hash Flashcards
When should Hash be used?
whenever you have keys and values.
What is a hash?
A Hash is a collection of key-value pairs
Show two ways of creating hashes. Code
empty_hash = Hash.new
empty_hash = {} # shorter and preferred
capitals = { ‘NY’ => ‘Albany’, ‘CA’ => ‘Sacramento’ }
What is code to look up a value of a key in a hash?
capitals = { ‘NY’ => ‘Albany’, ‘CA’ => ‘Sacramento’ }
capitals[‘NY’] # => ‘Albany’
How do you use each.do iteration for a hash? Code.
capitals = { ‘NY’ => ‘Albany’, ‘CA’ => ‘Sacramento’ }
capitals.each do |state, capital|
puts “#{capital} is the capital of #{state}”
end
How do you add a new key:value pair to a hash? code.
capitals[‘key string’] = ‘value string’
How do you delete a key:value pair in a hash? code.
capitals.delete(‘key string’)
How do you delete all key:value pairs in a hash that fulfill a certain logical test? code.
test_hash = {‘a’ => 100, ‘b’ => 25}
test_hash.delete_if {|key, value| value <= 50}
What is a RUBY symbol and why is it used?
- A Ruby symbol looks like “:mysymbol” and is an object that has both a number (integer) and a string.
- A symbol’s string name (after the colon) is also the its value.
- Use a string instead of a symbol unless you need immutability (cannot change at runtime).
- After the first usage of :mysymbol all further usages of :mysymbol take no further memory and are much faster than strings.
What is the method to combine two hashes? What is the code? And what happens when the two hashes have redundant data?
if you have two hashes with the same keys, duplicate entries in the merged Hash take precedence over the ones in the calling Hash
h1 = {:a => 'apple', :b => 'bat'} h2 = {:b => 'bravo', :c => 'charlie'}
h1.merge(h2) # => {:a => ‘apple’, :b => ‘bravo’, :c => ‘charlie’}
The method to find whether a hash contains a specific key?
capitals = { ‘New York’ => ‘Albany’, ‘California’ => ‘Sacramento’ }
capitals.has_key(‘New York’) # => true