2

I am new in Ruby, i am trying to declare a simple variable in ruby which can store int type value.

I have tried the following codes

var=5
puts var

and

@var=5
puts @var

The output in both program is 5 , can anybody explain what is the difference in both type of code.

sumit kumar
  • 602
  • 3
  • 11
  • 26

4 Answers4

5

You are talking about type of variables in ruby language.

var = 5 is local variable

and

@var  = 5 is instance variable 

The main difference between local and instance variable is that local variable is only available in controller, where as instance variable is available in corresponding views also. The controller and views do not share local variables.

For more details have look to below links:

Ruby Programming/Syntax/Variables and Constants

Variables in Ruby

Pravin Mishra
  • 8,298
  • 4
  • 36
  • 49
1

var is a local variable and @var is an instance variable

The main differences between local and instance variables are as follows

  1. local variable has its scope restriction i.e not available to another methods where as instance available to another
  2. local and instance variable is also available in view
  3. instance variable is separate for each object
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
0

@var is an instance variable, usually it is used in classes.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

var = 5 is local varibale and this is only accessible from within the block of its.

@var = 5 is instance varibale and an instance variable belongs to the object itself.

Dheer
  • 773
  • 1
  • 6
  • 16