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

Hash बनाना

एक hash एक key और इसकी value के pairs store करता है, एक dictionary की तरह जहाँ हर word का एक meaning है। एक बनाने के लिए आप curly braces इस्तेमाल करते हैं।

In this page:

  1. Hash Creation
Syntax
ruby
hash = { key1 => value1, key2 => value2 }
hash = Hash.new

Hash Creation

एक Ruby hash key-value pairs store करता है, curly braces से बनाया गया, { key => value } या modern symbol-key shorthand { key: value }।

Hashes Ruby का dictionary/map type हैं, आपको एक numeric index की बजाय एक arbitrary key से values lookup करने देते हुए। Keys आमतौर पर symbols या strings होती हैं, हालाँकि कोई भी object एक key की तरह काम कर सकता है।

Note: { key: value } shorthand सिर्फ तभी valid है जब keys symbols हों -- string keys को फिर भी => (rocket) syntax चाहिए।

उदाहरण: Hash Creation

markup
person = { name: "Alice", age: 30 }
old_style = { "name" => "Bob", "age" => 25 }

puts person.inspect
puts old_style.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. एक bare word के साथ { name => "Alice" } लिखना, जो name नाम का एक variable ढूंढता है; name: या :name => इस्तेमाल करें।
  2. same idea के लिए string और symbol keys mix करना, इसलिए lookups nil return करते हैं।
  3. एक JSON-style { "name": "Alice" } इस्तेमाल करना और एक string key की उम्मीद करना, जब Ruby इसे symbol :name में बदल देता है।
🔒

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.