Hashes पर each और map
Hashes पर each और map हर key और value pair से गुज़रते हैं, एक phone book में हर entry पढ़ने की तरह। each इनके साथ कुछ करता है, जबकि map इनसे एक नई list बनाता है।
In this page:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- एक hash पर
mapइस्तेमाल करना और वापस एक hash की उम्मीद करना, जब यह एक array return करता है;.to_hadd करें। - एक parameter
|pair|वाला एक block लिखना और सिर्फ key की उम्मीद करना, जब यह[key, value]receive करता है। - इसे iterate करते हुए एक hash बदलना, जो keys add होने पर एक error raise करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: