0Pricing
Ruby Academy · Lesson

Hash Iteration

each, map, select.

Iterating with each

The each method visits every pair. The block receives the key and value.

scores = { math: 90, art: 80 }
scores.each do |subject, score|
  puts "#{subject}: #{score}"
end

each_pair

each_pair is an alias of each for hashes. Use whichever reads clearer.

h = { a: 1, b: 2 }
h.each_pair { |k, v| puts "#{k}=#{v}" }

All lessons in this course

  1. Symbols vs Strings
  2. Creating and Reading Hashes
  3. Hash Iteration
  4. Default Values and Merging
← Back to Ruby Academy