Ruby

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 #<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

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

Advertisements

2 thoughts on “Ruby – Variables

  1. 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”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s