23. ➢ Global - $
➢ Instance - @
➢ Class - @@
➢ Local - [a-z] or _
➢ Constants - CAPS
Variables
24. Global Variables
$myvar = “Its is a Place”
class Chennai
def what_is_that
puts $myvar
end
end
class NewYork
def what_is_that
puts $myvar
end
end
Output:
chennai = Chennai.new
newyork = NewYork.new
chennai.what_is_that
newyork.what_is_that
--------------------------------------
Its is a Place
Its is a Place
25. Instance Variables
class Place
def initialize(place)
@current_place = place
end
def show_me
puts @current_place
end
end
Output:
chennai =Place.new(“Chennai”)
newyork = Place.new(“New York”)
chennai.show_me
newyork.show_me
--------------------------------------
Chennai
New York
26. Class Variables
@@hotels=0
class Place
def more_hotels
@@hotels +=1
end
end
Output:
chennai =Place.new
newyork = Place.new
chennai.more_hotels
newyork.more_hotels
--------------------------------------
1
2
27. Local Variables
Output:
chennai =Place.new(“Chennai”)
newyork = Place.new(“New York”)
chennai.show_me
newyork.show_me
--------------------------------------
Chennai
New York
Local Variable
class Place
def initialize(place)
@current_place = place
end
def show_me
puts @current_place
end
end
28. Constants
class Place
MYVAR = 100
def show_me
puts “Value of constant is #{MYVAR}”
end
end
Output:
chennai =Place.new(“Chennai”)
chennai.show_me
--------------------------------------
Value of constant is 100