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 O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.