← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 6 of 7

Symbols क्या हैं

एक symbol एक colon से शुरू होने वाला एक lightweight name है, एक label की तरह जिसका हमेशा same मतलब होता है। यह names और keys के लिए इस्तेमाल होता है क्योंकि यह quick है और कभी नहीं बदलता।

In this page:

  1. Symbols
Syntax
ruby
symbol = :name
hash = { name: value }

Symbols

:name की तरह लिखा एक symbol, एक immutable, interned identifier है -- एक string के उलट, same नाम वाले दो symbols हमेशा memory में exactly same object को refer करते हैं, इन्हें compare करने में तेज़ बनाते हुए।

Symbols आमतौर पर hash keys और method names की तरह इस्तेमाल होते हैं क्योंकि ये lightweight और unique हैं। ये ज़्यादातर दूसरी languages की तुलना में Ruby के ज़्यादा distinctive features में से एक हैं।

Note: Symbols strings से compare करने में तेज़ हैं (ये identity से compare होते हैं, character-by-character नहीं) यही वजह है ये hash keys के लिए idiomatic choice हैं।

उदाहरण: Symbols

markup
status = :active

puts status.class
puts :active.object_id == :active.object_id
puts "active".object_id == "active".object_id

person = { name: "Alice", role: :admin }
puts person[:name]
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. यह उम्मीद करना कि :active और "active" equal हैं, जब एक symbol और एक string अलग objects हैं।
  2. name: से बने hash के लिए person["name"] लिखना, जो nil return करता है क्योंकि key एक symbol है।
  3. old Ruby versions में user input से symbols बनाना, जो garbage collected नहीं हो सकते थे।
🔒

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.