Values को Access करना
आप square brackets से इसकी key माँगकर एक hash से एक value पाते हैं, एक dictionary में एक word लookup करने की तरह। अगर key वहाँ न हो, Ruby nil वापस देता है।
In this page:
Syntax
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
person = { name: "Alice", age: 30 }
puts person[:name]
puts person[:missing_key].inspect
puts person.fetch(:age)
puts person.fetch(:missing_key, "default value")
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. #}
आम गलतियां
person[:missing_key]पढ़ना और result इस्तेमाल करना जैसे यह exist करता हो, जब यहnilreturn करता है और बाद मेंNoMethodErrorcause कर सकता है।- एक missing key के लिए बिना default के
fetchइस्तेमाल करना, जोKeyErrorraise करता है। - एक symbol-key hash पर एक string key इस्तेमाल करना, जैसे
person["name"], जोnilreturn करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: