Ruby Hashes (Dictionary) Quiz

Ruby
0 Passed
0% acceptance

40 comprehensive questions exploring Ruby hash manipulation, key-value operations, and dictionary data structures — with 16 code examples covering hash creation, symbol vs string keys, iteration, and default values in this cpp quiz.

40 Questions
~80 minutes
1

Question 1

How do you create a basic hash in Ruby?

A
Using curly braces with key-value pairs separated by => or : for symbols
B
Only with the Hash.new method
C
Using square brackets
D
Hashes cannot be created directly
2

Question 2

What is the difference between symbol keys and string keys in Ruby hashes?

A
Symbol keys are immutable and faster for lookups while string keys are mutable and more flexible, affecting memory usage and performance in hash-intensive applications with repeated key access
B
They work identically in all cases
C
Symbol keys are slower than string keys
D
String keys are immutable, symbols are mutable
3

Question 3

When storing user configuration data where keys are known constants like database settings, which key type should you prefer?

ruby
config = { host: 'localhost', port: 5432, database: 'myapp' }
A
Use symbol keys for immutable configuration keys that are used repeatedly, providing better performance and memory efficiency compared to string keys for constant hash access patterns
B
Always use string keys for configuration
C
Key type doesn't matter for configuration
D
Use numbers for configuration keys
4

Question 4

How do you access values in a Ruby hash?

A
Using square bracket notation with the key, returning the value or nil if key doesn't exist, enabling safe hash access without exceptions for missing keys
B
Only with dot notation
C
Using parentheses
D
Hash values cannot be accessed directly
5

Question 5

What does the fetch method do compared to [] access?

ruby
hash = { a: 1, b: 2 }
value = hash.fetch(:c, 'default')
A
fetch raises KeyError for missing keys unless default provided while [] returns nil, offering explicit error handling versus silent nil returns for different error management strategies
B
They work identically
C
fetch only works with symbols
D
[] raises errors, fetch returns nil
6

Question 6

In a web application processing JSON API responses where keys come from external data, how should you handle key access?

A
Use string keys since JSON provides string keys, accessing with [] notation and handling nil returns appropriately, maintaining compatibility with external data formats and avoiding symbol conversion overhead
B
Convert all keys to symbols first
C
Use fetch for all JSON data
D
JSON data cannot be processed with hashes
7

Question 7

How do you add or update values in a hash?

A
Using bracket notation with assignment, creating new key-value pairs or updating existing ones, providing unified syntax for both insertion and modification operations
B
Only with special methods
C
Using push method
D
Hash values cannot be modified after creation
8

Question 8

What does the delete method do in Ruby hashes?

ruby
hash = { a: 1, b: 2, c: 3 }
removed = hash.delete(:b)
A
Removes key-value pair and returns the deleted value, modifying hash in place, enabling safe key removal with return value for further processing or validation
B
Deletes all keys
C
Returns the key instead of value
D
Delete only works with string keys
9

Question 9

How do you iterate over all key-value pairs in a hash?

A
Using each method which yields key-value pairs as arrays, enabling iteration over all entries for processing, transformation, or display operations with access to both keys and values
B
Only with loops
C
Using for loops only
D
Hash iteration is not supported
10

Question 10

When processing user profile data where you need to display all attributes, how should you iterate through the hash?

A
Use each_pair or each to iterate through key-value pairs, accessing both keys for labels and values for display, enabling dynamic profile rendering without hardcoding field names
B
Convert hash to array first
C
Use each_key and each_value separately
D
Profile data cannot be iterated
11

Question 11

What is a hash default value and how does it work?

ruby
hash = Hash.new('default')
value = hash[:missing]  # 'default'
A
Default value is returned for missing keys instead of nil, enabling graceful handling of unknown keys in lookup operations and providing fallback behavior for sparse data structures
B
Default values replace existing values
C
Default values are stored permanently
D
Hash default values are not supported
12

Question 12

How do you create a hash with a default block instead of a default value?

A
Pass block to Hash.new that computes default values dynamically, enabling context-aware defaults like creating new arrays or computing values based on the missing key itself
B
Default blocks are not supported
C
Use default_value method
D
Blocks can only be used with iteration
13

Question 13

What does the merge method do when combining hashes?

ruby
hash1 = { a: 1, b: 2 }
hash2 = { b: 3, c: 4 }
combined = hash1.merge(hash2)
A
Returns new hash with combined key-value pairs where second hash overwrites duplicate keys, preserving original hashes and enabling safe combination without side effects
B
Modifies the first hash in place
C
Only keeps unique keys
D
Merge only works with same key types
14

Question 14

In a configuration management system where you need to merge default settings with user overrides, which merge method should you use?

A
Use merge where user settings override defaults, creating layered configuration approach that allows customization while maintaining fallback to default values for unspecified settings
B
Use merge! to modify defaults in place
C
Never merge configurations
D
Use separate hashes for defaults and overrides
15

Question 15

How do you check if a key exists in a hash?

A
Using has_key? or key? methods which return true if key exists regardless of value, enabling safe key checking before access to avoid nil-related errors in conditional logic
B
Only by accessing the value and checking for nil
C
Using include? method
D
Hash key existence cannot be checked
16

Question 16

What does the select method do when working with hashes?

ruby
hash = { a: 1, b: 2, c: 3, d: 4 }
evens = hash.select { |k, v| v.even? }
A
Returns new hash with key-value pairs that match the block condition, enabling filtering operations that preserve hash structure while selecting specific entries based on keys and values
B
Modifies the original hash
C
Converts hash to array
D
Select only works with arrays
17

Question 17

When implementing a caching system where you need to store computation results with dynamic keys, how should you handle cache misses?

A
Use default block that computes and stores the value, enabling lazy evaluation where expensive operations only run once per unique key with automatic caching of results
B
Pre-compute all possible values
C
Use separate storage for cache misses
D
Caching cannot be implemented with hashes
18

Question 18

What is the difference between merge and merge! methods?

A
merge returns new hash while merge! modifies first hash in place, affecting whether original data is preserved or transformed directly for memory efficiency in hash combination operations
B
They work identically
C
merge! creates new hashes
D
merge modifies in place
19

Question 19

How do you iterate over only the keys of a hash?

ruby
hash = { a: 1, b: 2, c: 3 }
hash.each_key { |key| puts key }
A
Using each_key method which yields only keys to the block, enabling key-focused operations like validation, transformation, or processing without accessing values for efficiency
B
Using each method with index
C
Keys cannot be iterated separately
D
Using for loops only
20

Question 20

In a data validation system where you need to check that all required fields are present in user input, how should you validate hash keys?

A
Use all? with has_key? checks on required field list, ensuring comprehensive validation that all mandatory keys exist before processing user data and preventing incomplete submissions
B
Check each key individually with if statements
C
Use select to filter required fields
D
Hash validation is not needed
21

Question 21

What does the reject method do in Ruby hashes?

A
Returns new hash with key-value pairs that do not match the block condition, providing inverse filtering that excludes unwanted entries while preserving hash structure for data cleaning operations
B
Removes all entries from hash
C
Rejects only nil values
D
Reject only works with arrays
22

Question 22

When working with API responses that contain nested hash structures, how should you safely access deeply nested values?

A
Use dig method with multiple keys to safely navigate nested structures, returning nil for any missing intermediate keys instead of raising errors, enabling robust access to complex nested data
B
Use multiple [] accesses with error handling
C
Flatten the hash first
D
Nested hash access is not supported
23

Question 23

How do you transform all values in a hash while keeping the same keys?

ruby
hash = { a: 1, b: 2, c: 3 }
doubled = hash.transform_values { |v| v * 2 }
A
Using transform_values method which applies block to each value and returns new hash with transformed values, enabling value-level operations while preserving key structure and relationships
B
Using map method
C
Using each with assignment
D
Hash value transformation is not supported
24

Question 24

What does the invert method do to a hash?

A
Returns new hash with keys and values swapped, enabling reverse lookups where original values become keys and vice versa, useful for creating bidirectional mappings and lookup tables
B
Reverses the order of keys
C
Converts hash to array
D
Invert only works with numeric values
25

Question 25

In a multilingual application where you need to create reverse mappings from translated strings back to internal keys, how should you handle the hash inversion?

A
Use invert method to create reverse lookup hash, enabling efficient translation from display strings back to internal identifiers for form processing and data validation operations
B
Create separate reverse hash manually
C
Use arrays for reverse lookups
D
Reverse mappings are not needed
26

Question 26

How do you iterate over only the values of a hash?

ruby
hash = { a: 1, b: 2, c: 3 }
hash.each_value { |value| puts value }
A
Using each_value method which yields only values to the block, enabling value-focused operations like aggregation, validation, or processing without key context for efficiency
B
Using each method with destructuring
C
Values cannot be iterated separately
D
Using collect on hash
27

Question 27

When implementing a word frequency counter where you need to count occurrences of each word, how should you handle the counting logic?

A
Use default block that returns zero for missing keys, enabling increment operations with ||= or += syntax, providing automatic initialization and accumulation for frequency counting patterns
B
Pre-initialize all possible words
C
Use separate counter variables
D
Frequency counting cannot be done with hashes
28

Question 28

What does the compact method do when applied to hashes?

A
Returns new hash with all nil values removed, enabling data cleaning operations that eliminate missing or undefined values while preserving valid key-value pairs for data normalization
B
Removes all keys
C
Compacts hash in place
D
Compact only works with arrays
29

Question 29

How do you create a hash from two arrays, one with keys and one with values?

ruby
keys = [:a, :b, :c]
values = [1, 2, 3]
hash = keys.zip(values).to_h
A
Use zip method to pair corresponding elements then convert to hash with to_h, enabling creation of hashes from parallel arrays for data transformation and restructuring operations
B
Use Hash.new with arrays
C
Arrays cannot be converted to hashes
D
Use push method
30

Question 30

In a data processing pipeline where you need to filter hash entries based on complex conditions involving both keys and values, which method should you use?

A
Use select with block that receives both key and value parameters, enabling sophisticated filtering logic that can evaluate relationships between keys and values for advanced data processing requirements
B
Use find method
C
Use grep method
D
Complex filtering is not supported
31

Question 31

What does the keys method return for a hash?

A
Returns array containing all keys in insertion order, enabling key enumeration for iteration, validation, or extraction operations that work with key collections separately from values
B
Returns array of values
C
Returns hash size
D
Keys method is not supported
32

Question 32

When implementing a configuration system with environment-specific overrides, how should you merge multiple configuration hashes?

A
Use reverse_merge or merge with specific precedence order, ensuring environment settings override defaults while maintaining complete configuration coverage through layered hash combination
B
Use only one configuration hash
C
Merge all hashes randomly
D
Configuration merging is not supported
33

Question 33

How do you check if a hash is empty?

ruby
hash = {}
empty = hash.empty?
A
Using empty? method which returns true if hash contains no key-value pairs, providing clear boolean check for empty state validation in conditional logic and data processing workflows
B
Check if hash.size == 0
C
Check if hash.nil?
D
Hash empty state cannot be checked
34

Question 34

What does the values method return for a hash?

A
Returns array containing all values in key insertion order, enabling value enumeration for aggregation, validation, or extraction operations that work with value collections independently
B
Returns array of keys
C
Returns hash size
D
Values method is not supported
35

Question 35

In a caching system where you need to limit cache size by removing least recently used items, how should you implement the cache structure?

A
Use hash for O(1) lookups with ordered keys or timestamps, enabling efficient access and removal operations while maintaining recency information for cache management algorithms
B
Use arrays for caching
C
Use only timestamps without hash
D
LRU caching cannot be implemented with hashes
36

Question 36

What does the slice method do when used with hashes?

ruby
hash = { a: 1, b: 2, c: 3, d: 4 }
subset = hash.slice(:a, :c)
A
Returns new hash containing only specified keys and their values, enabling selective extraction of hash subsets for data filtering and partial object creation operations
B
Modifies the original hash
C
Converts hash to array
D
Slice only works with arrays
37

Question 37

When processing form data where multiple values can have the same name, how should you handle the resulting hash structure?

A
Web frameworks automatically create arrays for multiple values with same key, enabling direct array access for multi-select form fields and checkbox groups in parameter processing
B
Convert all values to strings
C
Use separate keys for each value
D
Multiple values are not supported in forms
38

Question 38

How do you sort a hash by its keys?

A
Use sort_by with key block to return sorted array of pairs, then convert back to hash with to_h, enabling ordered hash creation for display or serialization purposes with predictable key ordering
B
Hashes are always sorted
C
Use sort method directly
D
Hash sorting is not supported
39

Question 39

What does the fetch_values method do?

ruby
hash = { a: 1, b: 2, c: 3 }
values = hash.fetch_values(:a, :c)
A
Returns array of values for specified keys in order, raising KeyError for missing keys, providing strict value extraction that ensures all requested keys exist before processing
B
Returns hash with specified keys
C
Returns single value
D
Fetch_values only works with arrays
40

Question 40

Considering Ruby's hash handling ecosystem as a whole, what fundamental advantage do Ruby hashes provide compared to basic key-value stores in other languages?

A
Ruby combines rich built-in methods with flexible key types and default value support, creating an ecosystem where dictionary operations feel natural while maintaining performance through optimized implementation and comprehensive API coverage
B
Faster processing speed only
C
Automatic key sorting
D
Simpler syntax only