Bird
Raised Fist0
Rubyprogramming~10 mins

Hash methods (keys, values, each) in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Hash methods (keys, values, each)
Start with a Hash
↓
Call keys method
→Get array of keys
↓
Call values method
→Get array of values
↓
Call each method
→Iterate each key-value pair
↓
Perform action inside block
↓
End
This flow shows how to get keys, values, and iterate over each key-value pair in a Ruby hash.
Execution Sample
Ruby
my_hash = {a: 1, b: 2, c: 3}
keys = my_hash.keys
values = my_hash.values
my_hash.each do |key, value|
  puts "#{key}: #{value}"
end
This code gets keys and values arrays from a hash and prints each key-value pair.
Execution Table
StepActionEvaluationResult/Output
1Create hash my_hashmy_hash = {a:1, b:2, c:3}{:a=>1, :b=>2, :c=>3}
2Call keys methodmy_hash.keys[:a, :b, :c]
3Call values methodmy_hash.values[1, 2, 3]
4Start each iteration, first pairkey = :a, value = 1Prints 'a: 1'
5Second iterationkey = :b, value = 2Prints 'b: 2'
6Third iterationkey = :c, value = 3Prints 'c: 3'
7End each iterationNo more pairsIteration ends
💡 All key-value pairs processed, iteration ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 7
my_hashnil{:a=>1, :b=>2, :c=>3}{:a=>1, :b=>2, :c=>3}{:a=>1, :b=>2, :c=>3}
keysnil[:a, :b, :c][:a, :b, :c][:a, :b, :c]
valuesnilnil[1, 2, 3][1, 2, 3]
keynilnilnilnil (used inside each)
valuenilnilnilnil (used inside each)
Key Moments - 3 Insights
Why does keys return an array of symbols, not a hash?
The keys method extracts only the keys from the hash and returns them as an array, as shown in step 2 of the execution_table.
What does the each method do with the key and value variables?
The each method assigns each key and value pair to the block variables key and value in each iteration, as shown in steps 4 to 6.
Does calling values change the original hash?
No, calling values returns an array of values without modifying the original hash, as seen in step 3 and variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the output of my_hash.values?
A[:a, :b, :c]
B[1, 2, 3]
C{:a=>1, :b=>2, :c=>3}
Dnil
💡 Hint
Check the 'Result/Output' column at step 3 in the execution_table.
At which step does the each method print 'b: 2'?
AStep 5
BStep 6
CStep 4
DStep 7
💡 Hint
Look at the 'Action' and 'Result/Output' columns for each iteration in the execution_table.
If the hash was empty, what would keys return?
Anil
BAn array with nil elements
CAn empty array []
DAn error
💡 Hint
Recall that keys returns an array of keys; if no keys exist, it returns an empty array.
Concept Snapshot
Hash methods in Ruby:
- keys returns an array of all keys
- values returns an array of all values
- each iterates over key-value pairs
Use each with a block: hash.each do |key, value| ... end
These methods do not modify the original hash.
Full Transcript
This visual execution shows how Ruby hash methods keys, values, and each work. First, a hash with three pairs is created. Calling keys returns an array of the keys :a, :b, and :c. Calling values returns an array of the values 1, 2, and 3. The each method loops over each key-value pair, assigning them to block variables key and value, and prints them. The iteration stops after all pairs are processed. The keys and values methods do not change the original hash. This step-by-step trace helps beginners see how these methods work and how variables change during execution.

Practice

(1/5)
1. What does the keys method do when called on a Ruby hash?
easy
A. Deletes all keys from the hash
B. Returns an array of all the values in the hash
C. Returns an array of all the keys in the hash
D. Iterates over each key-value pair in the hash

Solution

  1. Step 1: Understand the keys method

    The keys method extracts all keys from the hash and returns them as an array.
  2. Step 2: Compare with other methods

    values returns values, each iterates pairs, so only keys returns keys array.
  3. Final Answer:

    Returns an array of all the keys in the hash -> Option C
  4. Quick Check:

    keys = keys array [OK]
Hint: Remember: keys method lists all keys as an array [OK]
Common Mistakes:
  • Confusing keys with values method
  • Thinking keys modifies the hash
  • Mixing up keys with each method
2. Which of the following is the correct syntax to iterate over each key-value pair in a Ruby hash h?
easy
A. h.each(key, value) { puts key, value }
B. h.each { |key, value| puts key + value }
C. h.each do |key value| puts key, value end
D. h.each { key, value -> puts key + value }

Solution

  1. Step 1: Identify correct block syntax for each

    The correct syntax uses curly braces or do-end with block parameters separated by a comma inside pipes: { |key, value| ... }.
  2. Step 2: Check each option

    h.each { |key, value| puts key + value } uses correct syntax with pipes and comma. Others have syntax errors or wrong block format.
  3. Final Answer:

    h.each { |key, value| puts key + value } -> Option B
  4. Quick Check:

    Correct block syntax = h.each { |key, value| puts key + value } [OK]
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

  1. 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.
  2. 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.
  3. Final Answer:

    [:a, :b, :c] -> Option D
  4. 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

  1. Step 1: Check block parameter syntax

    Block parameters must be separated by a comma inside pipes: |k, v|. Here comma is missing.
  2. Step 2: Verify other parts

    Keys as symbols are valid, each do-end is valid, and puts syntax is correct.
  3. Final Answer:

    Missing comma between block parameters k and v -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    h.select { |k, v| v }.keys -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard