Ruby Intro - Hash Flashcards

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

When should Hash be used?

A

whenever you have keys and values.

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

What is a hash?

A

A Hash is a collection of key-value pairs

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

Show two ways of creating hashes. Code

A

empty_hash = Hash.new

empty_hash = {} # shorter and preferred

capitals = { ‘NY’ => ‘Albany’, ‘CA’ => ‘Sacramento’ }

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

What is code to look up a value of a key in a hash?

A

capitals = { ‘NY’ => ‘Albany’, ‘CA’ => ‘Sacramento’ }

capitals[‘NY’] # => ‘Albany’

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

How do you use each.do iteration for a hash? Code.

A

capitals = { ‘NY’ => ‘Albany’, ‘CA’ => ‘Sacramento’ }

capitals.each do |state, capital|
puts “#{capital} is the capital of #{state}”
end

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

How do you add a new key:value pair to a hash? code.

A

capitals[‘key string’] = ‘value string’

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

How do you delete a key:value pair in a hash? code.

A

capitals.delete(‘key string’)

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

How do you delete all key:value pairs in a hash that fulfill a certain logical test? code.

A

test_hash = {‘a’ => 100, ‘b’ => 25}

test_hash.delete_if {|key, value| value <= 50}

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

What is a RUBY symbol and why is it used?

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

What is the method to combine two hashes? What is the code? And what happens when the two hashes have redundant data?

A

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’}

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

The method to find whether a hash contains a specific key?

A

capitals = { ‘New York’ => ‘Albany’, ‘California’ => ‘Sacramento’ }

capitals.has_key(‘New York’) # => true

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