Symbol vs String में अंतर
Symbols और strings दिखने में similar हैं, लेकिन एक symbol एक single unchangeable label है जबकि एक string editable text है। names के लिए symbols और बदल सकने वाले words के लिए strings इस्तेमाल करें।
In this page:
Syntax
symbol = :name
string = "name"
symbol.object_id == :name.object_id # true
string.object_id == "name".object_id # false
Symbol बनाम String
Symbols (:name) immutable और memory-efficient identifiers हैं जो hash keys, method names, और options के fixed sets जैसी चीज़ों के लिए सबसे अच्छे हैं, जबकि strings ("name") actual text data के लिए हैं जो बदल या manipulate हो सकता है।
एक common rule of thumb: अगर value user-facing text की बजाय एक identifier या category represent करती है, एक symbol आमतौर पर बेहतर fit है। इनके बीच convert करना .to_sym और .to_s से आसान है।
Note:
Rule of thumb: identifiers/categories के लिए एक symbol इस्तेमाल करें (जैसे :active), और actual text data के लिए एक string (जैसे किसी person का नाम)।
उदाहरण: Symbol vs String
status = :active # identifier -- symbol fits well
name = "Alice" # actual text data -- string fits well
puts status.to_s
puts name.to_sym.inspect
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. #}
आम गलतियां
- hash keys की तरह strings इस्तेमाल करना जहाँ symbols intended हों, इसलिए lookups
nilreturn करते हैं। to_symसे user text को एक symbol में convert करना और इसे modify करने की उम्मीद करना, जब symbols immutable हैं।- यह उम्मीद करना कि
"a".object_idहर बार equal होगा, जब हर string literal एक नया object है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: