What is the difference between instance variables and local variables?

Instance variables and local variables both are frquently used in ruby and rails programming. Both have some difference between them and not only in ways of defining them but also in their usage and scopes as well.

# Instance Variables Local Variables
1 An instance variable always starts with an @ symbol. For example: @array = Array.new() or @array = []. Both represents an instance variable. A local variable always starts with a lowercase character. Defining a local variable name is same as defining a method in Ruby. For example array = Array.new()
2 An instance variable is accessible by all the methdos defined by it's class hence it's scope is entire class. A local variable has limited scope than an instance variable. It can be accessible only within the block(methods, iterators, loops) it is defined.
3 Accessing an undefined or uninitialized instance variable never return any error. Instead of error it always return nil. Accessing an undefined local variable always returns an error. So when using local variables you need make sure that it is defined.

APPSIMPACT Academy

Ruby on Rails is a very popular and most productive web application development framework. At APPSIMPACT Academy we provide best content to learn Ruby on Rails framework.

Questions & Answers
What is the difference between instance variables and local variables? What is initialize() method in Ruby? What are getter and setter methods in Ruby? Comparision between rails 4, 5 and 6 What is difference between sub and gsub in Ruby? How to recreate flatten method in Ruby using recursion?