5.7. Iterowanie po zawartości hasza

Problem

Dla danego hasza chcemy wykonać iterację po jego elementach, tak jakby były to elementy tablicy.

Rozwiązanie

Iterację tę można wykonać za pomocą iteratora Hash#each_pair lub Hash#each. Każdy z nich udostępnia kolejno wszystkie pary „klucz-wartość”.

hash = { 1 => 'jeden', [1,2] => 'dwa', 'trzy' => 'trzy' } hash.each_pair { |key, value| puts "#{key.inspect} mapowane jest w #{value}"} # [1, 2] mapowane jest w dwa # 1 mapowane jest w jeden # "trzy" mapowane jest w trzy hash.each{ |key, value| puts "#{key.inspect} mapowane jest w #{value}"} # [1, 2] mapowane jest w dwa # 1 mapowane jest w jeden # "trzy" mapowane jest w trzy hash.each{ |item| puts item[0].to_s + ' mapowane jest w ' + item[1].to_s ...

Get Ruby. Receptury now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.