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

Symbol Keys का इस्तेमाल

Symbol keys एक hash में labels की तरह :name जैसे names इस्तेमाल करती हैं, जो usual Ruby habit है। यह drawer labels की तरह short, reusable tags इस्तेमाल करने जैसा है।

In this page:

  1. Symbol Keys
Syntax
ruby
hash = { name: value1, other_name: value2 }
hash[:name]

Symbol Keys

Hash keys की तरह symbols (:name) इस्तेमाल करना idiomatic Ruby convention है, क्योंकि symbols immutable हैं और strings से तेज़ compare होते हैं।

Shorthand { name: "Alice" } syntax specifically symbol keys के लिए है और { :name => "Alice" } के बराबर है। same hash में symbol और string keys mix करना legal है लेकिन usually inconsistent design का एक sign है।

Note: { name: "Alice" } और { :name => "Alice" } exactly equivalent हैं -- colon-shorthand बस newer, ज़्यादा concise syntax है।

उदाहरण: Symbol Keys

markup
options = { color: "red", size: "large" }
same_thing = { :color => "red", :size => "large" }

puts options == same_thing
puts options[:color]
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. "color" और :color को keys की तरह mix करना, इसलिए options["color"] nil return करता है।
  2. बिना colon के { color => "red" } लिखना, जो color नाम का एक variable ढूंढता है।
  3. short form में spaces या dashes वाली keys इस्तेमाल करना जैसे { first-name: 1 }, जो एक syntax error है; "first-name": 1 या :"first-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.