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

merge क्या है

merge दो hashes को एक में combine करता है, दो contact lists जोड़ने की तरह। अगर दोनों के पास same key हो, दूसरे की value जीतती है।

In this page:

  1. merge
Syntax
ruby
combined = hash1.merge(hash2)
combined = hash1.merge(hash2) { |key, old, new| old + new }

merge

hash1.merge(hash2) दो hashes को एक नए में combine करता है, जो भी keys ये share करती हैं उनके लिए hash2 की values hash1 की को overwrite करते हुए।

merge! same combination perform करता है लेकिन एक नया hash return करने की बजाय hash1 को in place mutate करता है। एक block form आपको customize करने देता है कि conflicting keys कैसे resolve हों बजाय सिर्फ दूसरे hash की value लेने के।

Note:
  • merge एक नया hash return करता है और original unchanged छोड़ता है।
  • merge! (या update) receiver को in place mutate करता है।

उदाहरण: merge

markup
defaults = { color: "blue", size: "medium" }
overrides = { size: "large" }

result = defaults.merge(overrides)
puts result.inspect
puts defaults.inspect  # unchanged
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. यह उम्मीद करना कि merge defaults बदल देगा, जब यह एक नया hash return करता है जब तक आप merge! या update इस्तेमाल न करें।
  2. order गलत करना, इसलिए overrides.merge(defaults) defaults को आपकी custom values overwrite करने देता है।
  3. string keys और symbol keys इस्तेमाल करने वाले hashes merge करना, इसलिए same setting दो बार appear होती है।
🔒

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.