Symbols क्या हैं
एक symbol एक colon से शुरू होने वाला एक lightweight name है, एक label की तरह जिसका हमेशा same मतलब होता है। यह names और keys के लिए इस्तेमाल होता है क्योंकि यह quick है और कभी नहीं बदलता।
In this page:
Syntax
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
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]
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. #}
आम गलतियां
- यह उम्मीद करना कि
:activeऔर"active"equal हैं, जब एक symbol और एक string अलग objects हैं। name:से बने hash के लिएperson["name"]लिखना, जोnilreturn करता है क्योंकि key एक symbol है।- old Ruby versions में user input से symbols बनाना, जो garbage collected नहीं हो सकते थे।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: