Bird
Raised Fist0
Rubyprogramming~3 mins

Why Hash methods (keys, values, each) in Ruby? - Purpose & Use Cases

Choose your learning style10 modes available
The Big Idea

What if you could instantly see all parts of your data without digging through it one by one?

The Scenario

Imagine you have a big box full of labeled jars, and you want to find all the jar labels, or maybe just the contents inside each jar. Doing this by hand means opening each jar one by one and writing down what you find.

The Problem

Manually checking each jar is slow and tiring. You might miss some jars or write down wrong labels. If the box is huge, it becomes a big headache to keep track of everything without mistakes.

The Solution

Hash methods like keys, values, and each let you quickly list all labels, all contents, or go through each jar easily. This saves time and avoids errors by automating the process.

Before vs After
✗ Before
puts hash["name"]
puts hash["age"]
puts hash["city"]
✓ After
hash.keys.each { |key| puts key }
hash.values.each { |value| puts value }
hash.each { |key, value| puts "#{key}: #{value}" }
What It Enables

It lets you explore and use all parts of your data quickly and safely, making your programs smarter and easier to write.

Real Life Example

Think of a contact list where you want to print all names, or all phone numbers, or both together. Using these methods, you can do it in just a few lines instead of searching one by one.

Key Takeaways

Manual searching through data is slow and error-prone.

Hash methods automate accessing keys, values, or both.

This makes working with data faster, safer, and simpler.

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