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

Values को Access करना

आप square brackets से इसकी key माँगकर एक hash से एक value पाते हैं, एक dictionary में एक word लookup करने की तरह। अगर key वहाँ न हो, Ruby nil वापस देता है।
Syntax
ruby
hash[key]
hash.fetch(key)
hash.fetch(key, default_value)
hash[key] = new_value

Values Access करना

एक hash value square brackets से पढ़ी जाती है, hash[key], जो एक error raise करने की बजाय key exist न करने पर nil return करता है।

.fetch(key) एक stricter alternative है जो एक missing key के लिए KeyError raise करता है, या दूसरे argument की तरह एक default accept करता है। [] और .fetch के बीच चुनना इस पर depend करता है कि एक missing key को एक error की तरह treat होना चाहिए या नहीं।

Note: जब एक missing key को एक bug की तरह treat होना चाहिए, चुपचाप nil return करने की बजाय, [] की बजाय .fetch(key) इस्तेमाल करें।

उदाहरण: Accessing Values

markup
person = { name: "Alice", age: 30 }

puts person[:name]
puts person[:missing_key].inspect

puts person.fetch(:age)
puts person.fetch(:missing_key, "default value")
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. person[:missing_key] पढ़ना और result इस्तेमाल करना जैसे यह exist करता हो, जब यह nil return करता है और बाद में NoMethodError cause कर सकता है।
  2. एक missing key के लिए बिना default के fetch इस्तेमाल करना, जो KeyError raise करता है।
  3. एक symbol-key hash पर एक string key इस्तेमाल करना, जैसे person["name"], जो nil return करता है।
🔒

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.