Ruby – Variables
November 12, 2009
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 #<Ordin:0xb7d3c5e0> (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
———————————————-
March 18, 2010 at 9:30 am
hi ravi,
cool stuff, this will give clear idea about ruby variables. If you don’t mind one small information
replace the 2nd Scenario heading – instead of “Method variable” you can use “Instance variable” “object variable”
March 22, 2010 at 3:21 pm
Sure Veera. Will change it….