← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 3 of 6

Symbol vs String में अंतर

Symbols और strings दिखने में similar हैं, लेकिन एक symbol एक single unchangeable label है जबकि एक string editable text है। names के लिए symbols और बदल सकने वाले words के लिए strings इस्तेमाल करें।
Syntax
ruby
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

markup
status = :active     # identifier -- symbol fits well
name = "Alice"       # actual text data -- string fits well

puts status.to_s
puts name.to_sym.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. hash keys की तरह strings इस्तेमाल करना जहाँ symbols intended हों, इसलिए lookups nil return करते हैं।
  2. to_sym से user text को एक symbol में convert करना और इसे modify करने की उम्मीद करना, जब symbols immutable हैं।
  3. यह उम्मीद करना कि "a".object_id हर बार equal होगा, जब हर string literal एक नया object है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.