Hint: Use pipes and commas inside block for key-value pairs [OK]
Common Mistakes:
Omitting pipes around block parameters
Missing comma between key and value
Using arrow syntax incorrectly in blocks
3. What will be the output of the following Ruby code?
h = {a: 1, b: 2, c: 3}
h.keys
medium
A. [:1, :2, :3]
B. [1, 2, 3]
C. {a: 1, b: 2, c: 3}
D. [:a, :b, :c]
Solution
Step 1: Understand keys method on hash
The keys method returns an array of all keys in the hash. Here keys are symbols :a, :b, :c.
Step 2: Match output with options
[:a, :b, :c] matches the array of keys. [1, 2, 3] is values, C is the whole hash, D is invalid symbol array.
Final Answer:
[:a, :b, :c] -> Option D
Quick Check:
h.keys = [:a, :b, :c] [OK]
Hint: keys returns array of keys exactly as in hash [OK]
Common Mistakes:
Confusing keys with values output
Expecting hash instead of array
Misreading symbols as strings
4. Identify the error in the following Ruby code snippet:
h = {x: 10, y: 20}
h.each do |k v|
puts "#{k}: #{v}"
end
medium
A. Missing comma between block parameters k and v
B. Hash keys must be strings, not symbols
C. The each method cannot be used with do-end
D. The puts statement syntax is incorrect
Solution
Step 1: Check block parameter syntax
Block parameters must be separated by a comma inside pipes: |k, v|. Here comma is missing.
Step 2: Verify other parts
Keys as symbols are valid, each do-end is valid, and puts syntax is correct.
Final Answer:
Missing comma between block parameters k and v -> Option A
Quick Check:
Block params need comma [OK]
Hint: Always separate block parameters with commas inside pipes [OK]
Common Mistakes:
Omitting comma between block variables
Thinking symbols are invalid keys
Confusing block syntax with method call
5. Given the hash h = {a: 1, b: 0, c: nil, d: 4}, which code snippet correctly returns an array of keys whose values are truthy (not false or nil)?
hard
A. h.select { |k, v| v }.keys
B. h.keys.select { |k| k }
C. h.values.select { |v| v }.keys
D. h.each { |k, v| k if v }.keys
Solution
Step 1: Understand filtering keys by truthy values
We want keys where values are truthy (not false or nil). select filters pairs by value truthiness.
Step 2: Analyze each option
h.select { |k, v| v }.keys filters hash pairs by truthy value, then gets keys -> [:a, :d] [check]. h.keys.select { |k| k } checks if key truthy (all symbols are), returns all keys. h.values.select { |v| v }.keys calls keys on array (NoMethodError). h.each { |k, v| k if v }.keys returns original hash, no filtering.
Final Answer:
h.select { |k, v| v }.keys -> Option A
Quick Check:
Filter pairs then get keys = h.select { |k, v| v }.keys [OK]
Hint: Use select on hash then call keys to filter by values [OK]
Common Mistakes:
Trying to call keys on array of values
Using each instead of select for filtering
Selecting keys without checking values
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.