Variable in Ruby

Tram Ho

1. Variable scope in Ruby

Scope defines where a variable is accessible in the program. Knowing the scope of each variable in the program will be very helpful in avoiding errors and debugging. In Ruby, there are 4 types of scope: local, global, instance and class. Besides Ruby has more Constant variables. In Ruby each variable type has a separate starting character:

Character startsVariable scope
[az] or _Local variable
$Global variable
@Instance variable
@@Class variable

So you can specify the variable type based only and the first character of the variable. But what about the other way, is to use the defined? method defined?

2. Local variable

Local variable is a Local variable that begins with the character [az] or _ . The accessibility of the local variable depends on where it is declared. For example, when declaring local variables in a class, mehtod or loop, you will not be able to access local variables outside of that class, method or loop.

When run will produce results

2. Global variable

Global variable in Ruby begin with the character $ . Global variables can be accessed from anywhere in the program.

When run will give results

3. Instance variable

Instance variable in Ruby begin with the @ character. It only belongs to an individual object or an object of a class.

When run will give results

As the example above we see instance variables only properties for each object and its use scope is entirely in the class.

4. Class variable

Class variable in Ruby begin with the character @@ . Class variable can be accessed in all instances of that class. Another with Global variable operating range is the latest program, Class variable with the scope of activities that are in the class.

When run will give results

5. Constant

Constant in Ruby begins with a capital letter [AZ] . Constant in Ruby is similar to a variable, but the only thing is that its value is not changed. The Ruby interpreter is not required to fix Constant ‘s value, but if there is a change in Constant ‘s value, the interpreter will notify you of that change.

Reference source

Share the news now

Source : Viblo