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

Frozen String Literals क्या हैं

बिल्कुल top पर एक special comment file में हर text को locked बना सकता है ताकि इसे बदला न जा सके। यह आपके सारे notes laminate करने जैसा है ताकि कोई इन पर scribble न कर सके।

In this page:

  1. Frozen String Literals
Syntax
ruby
# frozen_string_literal: true

string = "literal"    # frozen, cannot be modified

Frozen String Literals

एक Ruby file की बिल्कुल पहली line की तरह # frozen_string_literal: true add करना उस file में हर string literal को default से frozen (immutable) बनाता है, जो unnecessary string object allocation avoid करके performance improve कर सकता है।

यह अब Ruby projects और gems में एक common convention है। Individual strings एक mutable copy पाने के लिए .dup call करके अभी भी explicitly unfrozen हो सकती हैं।

Note: अगर आपको specifically इसकी एक mutable copy चाहिए एक frozen string पर .dup call करें।

उदाहरण: Frozen String Literals

markup
# frozen_string_literal: true

name = "Alice"
puts name.frozen?

mutable_copy = name.dup
puts mutable_copy.frozen?
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. # frozen_string_literal: true comment को दूसरी lines के बाद रखना, जब इसे काम करने के लिए top पर होना ज़रूरी है।
  2. बाद में << से एक string modify करना, जो FrozenError raise करता है; dup या +"" इस्तेमाल करें।
  3. यह मान लेना कि यह हर case में interpolated strings freeze करता है, जब यह सिर्फ बिना interpolation वाले literals पर apply होता है।
🔒

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.