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

Local, Global, Instance और Class Variables

Ruby में अलग-अलग तरह के variables हैं जो अलग-अलग जगहों पर देखे जा सकते हैं: कुछ सिर्फ एक spot में, कुछ एक object के अंदर, कुछ पूरी class में, और कुछ हर जगह। यह एक desk drawer, एक bedroom shelf, एक family cupboard, और एक town notice board रखने जैसा है।
Syntax
ruby
local_var = value
$global_var = value
@instance_var = value
@@class_var = value

Local, Global, Instance, और Class Variables

Ruby naming convention से variable scope अलग करता है: local_var अपने block/method के लिए local है, $global_var हर जगह accessible है, @instance_var एक specific object से belong करता है, और @@class_var एक class के सारे instances में shared है।

यह prefix-based naming Ruby को ज़्यादातर दूसरी languages की तुलना में unique बनाती है, जो इसकी बजाय separate declaration keywords इस्तेमाल करती हैं। Global variables practice में rarely इस्तेमाल होते हैं क्योंकि ये code के बारे में reason करना मुश्किल बनाते हैं।

Warning: Global variables ($var) Ruby में almost हमेशा bad practice माने जाते हैं -- एक object या class तक scoped instance या class variables prefer करें।

उदाहरण: Local, Global, Instance, and Class Variables

markup
$global_count = 0

class Counter
  @@total_counters = 0

  def initialize
    @count = 0
    @@total_counters += 1
    $global_count += 1
  end
end

Counter.new
Counter.new

puts "Total counters created: #{Counter.class_variable_get(:@@total_counters)}"
puts "Global count: #{$global_count}"
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. एक method के अंदर एक local variable इस्तेमाल करना जो इसके बाहर defined था, जो NameError raise करता है क्योंकि methods outer locals नहीं देखते।
  2. @@count class variables इस्तेमाल करना और यह देखकर surprised होना कि subclasses इन्हें share करती हैं।
  3. एक instance में एक uninitialised @count पढ़ना, जो एक error की बजाय nil देता है।
🔒

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.