Variable declaration in Ruby

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.

Local Variable:

Always start with lowercase or underscore ( _ ). It works only in the variable declared block. For example,

module display
    str  = "This is Local Variable"
end

Class Variable:

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

Output:

Hello!

Instance Variable:

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

Output:

Hello!
RJ!

Global variable:

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

Output:

Pruthviraj

I hope you guys found this page helpful 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.