Ruby – Variables

Scenario 1: Local variable

class Ordin
def first
a=10
puts a
end
def second
puts a
end
end

obj=Ordin.new
obj.first
obj.second

output:

variable_explanation.rb:11:in `second’: undefined local variable or method `a’ for # (NameError)
from variable_explanation.rb:17

10

Description:
a –> works only inside of first method

———————————————-

Scenario 2: Method variable

class Metho
def first
@a=10
puts “#{@a} from first method”
end
def second
puts “#{@a} from second method”
end
end

obj=Metho.new
obj.first
obj.second

output:

10 from first method
10 from second method

———————————————-

Scenario 3: Class Variable

class One
@@a=10
def first
puts “#{@@a=@@a+3} from first method”
end
def second
puts “#{@@a} from second method”
end
end

class Two < One
def third
puts @@a
end
end

obj=Two.new
obj.third

Ouput:

10

———————————————-

Scenario 4: Global Variable

class One
$a=10
def first
puts “#{$a} from first method”
end
def second
puts “#{$a} from second method”
end
end

class Two
def third
puts $a
end
end

obj=Two.new
obj.third

Ouput:

10

———————————————-