← Back to Ruby Course | Chapter 5: Hashes | Lesson 3 of 7

Hashes पर each और map

Hashes पर each और map हर key और value pair से गुज़रते हैं, एक phone book में हर entry पढ़ने की तरह। each इनके साथ कुछ करता है, जबकि map इनसे एक नई list बनाता है।
Syntax
ruby
hash.each { |key, value| # body }
result = hash.map { |key, value| expression }

Hashes पर each और map

hash.each { |key, value| ... } हर key-value pair पर iterate करता है, और hash.map { |key, value| ... } हर pair को एक नए array element में transform करता है (एक नए hash में नहीं, जब तक आप .to_h follow न करें)।

यह arrays पर इस्तेमाल होने वाले same enumeration style को mirror करता है। दोनों एक hash की हर entry process करने का standard तरीका हैं।

Note: एक hash पर map block के results का एक array return करता है -- अगर आपको वापस एक hash चाहिए बाद में .to_h chain करें।

उदाहरण: each and map on Hashes

markup
ages = { alice: 30, bob: 25, cara: 40 }

ages.each { |name, age| puts "#{name} is #{age}" }

doubled_ages = ages.map { |name, age| [name, age * 2] }.to_h
puts doubled_ages.inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक hash पर map इस्तेमाल करना और वापस एक hash की उम्मीद करना, जब यह एक array return करता है; .to_h add करें।
  2. एक parameter |pair| वाला एक block लिखना और सिर्फ key की उम्मीद करना, जब यह [key, value] receive करता है।
  3. इसे iterate करते हुए एक hash बदलना, जो keys add होने पर एक error raise करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.