We can describe the variable in 4 different types :
- Local variable
- Class variable
- Instance variable
- Global variable
Let’s check, How variable works in their comfort zones.
Always start with lowercase or underscore ( _ ). It works only in the variable declared block. For example,
module display str = "This is Local Variable" end
Always start with @@ and name of the variable. It accessible in the whole class. it must be initialized before use. It changes value each time it used. Without the initialized variable declaration it returns an error.
class A @@var = 'Hello!' def self.dis puts @@var end end A.dis
Always start with @ sign. Accessible in a class and any instance of class. No need to initialize. Without initialize it returns Nil.
class A @var = 'Hello!' def self.dis puts @var end end A.dis class B < A @var = 'RJ!' end B.dis
Always start with $ sign. use this variable anywhere in a program. Uninitiated variable returns Nil. There are lot of predefined global variables available in ruby. So, Make sure before use.
$name = "Pruthviraj" puts $name
I hope you guys found this page helpful 🙂