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

Default Values क्या हैं

एक default value एक hash को उन keys के लिए एक backup answer देता है जो इसके पास नहीं हैं, एक helper की तरह जो कहता है zero अगर list में एक नाम न हो। यह कुछ भी वापस न पाने से बचाता है।

In this page:

  1. Default Values
Syntax
ruby
hash = Hash.new(default_value)
hash[missing_key]    # returns default_value

Default Values

Hash.new(default_value) एक hash बनाता है जो एक missing key access करने पर nil की बजाय एक specified default return करता है, actually उस key को hash में add किए बिना।

Hash.new { |hash, key| ... } एक block form लेता है जो dynamically एक default compute कर सकता है, और optionally इसे hash में insert कर सकता है। यह counters बनाने या हर बार manually nil check किए बिना data group करने की एक common technique है।

Note: Hash.new(0) एक counting hash के लिए classic idiom है -- counts[word] += 1 पहले key exist करती है या नहीं check किए बिना तुरंत काम करता है।

उदाहरण: Default Values

markup
counts = Hash.new(0)

words = ["apple", "banana", "apple", "cherry", "apple"]
words.each { |word| counts[word] += 1 }

puts counts.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. एक array default के लिए Hash.new([]) इस्तेमाल करना, जहाँ सारी keys same array share करती हैं; Hash.new { |h, k| h[k] = [] } इस्तेमाल करें।
  2. यह उम्मीद करना कि एक plain lookup से एक missing key add होगी, जब Hash.new(0) इसे store किए बिना default return करता है।
  3. यह भूल जाना कि += 1 को एक default चाहिए, इसलिए counts[word] += 1 default nil पर NoMethodError raise करता है।
चैप्टर सारांश
  • Hashes key-value pairs store करते हैं, और आप key से values access करते हैं।
  • each, map, select, reject, और merge hashes process करते हैं।
  • Symbol keys और default values hashes को convenient बनाते हैं।
🔒

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.