1. Introduction
Hashes are a fundamental data structure in Ruby, storing key-value pairs. Iterating over a hash allows developers to access each of these pairs, and Ruby provides several methods to do so. This guide will present different ways to iterate over a hash in Ruby.
2. Program Steps
1. Create a hash with multiple key-value pairs.
2. Use various methods, including each, each_key, and each_value, to iterate over the hash.
3. Within each iteration, print out relevant data from the hash.
3. Code Program
# Creating a hash with key-value pairs sample_hash = { "name" => "John", "age" => 28, "job" => "Developer", "city" => "San Francisco" } # Using the each method to iterate over key-value pairs puts "Using each method:" sample_hash.each do |key, value| puts "#{key}: #{value}" end # Using the each_key method to iterate over keys puts "\nUsing each_key method:" sample_hash.each_key do |key| puts "Key: #{key}" end # Using the each_value method to iterate over values puts "\nUsing each_value method:" sample_hash.each_value do |value| puts "Value: #{value}" end
Output:
Using each method: name: John age: 28 job: Developer city: San Francisco Using each_key method: Key: name Key: age Key: job Key: city Using each_value method: Value: John Value: 28 Value: Developer Value: San Francisco
Explanation:
- The each method in Ruby provides a way to traverse both keys and values in a hash. By providing two block variables (like key and value), you can access and use both within the block.
- The each_key method specifically iterates only over the keys of the hash, disregarding the values.
- Similarly, each_value focuses on the values in the hash, skipping the keys.
By understanding and using these methods, you can control how you iterate over a hash based on your specific needs.
Comments
Post a Comment