Variables in Ruby

Here just how’s  to declare global, class, instant, and local variables in Ruby:


$global_variable = "global variable"

class First
    @@class_variable = 0

    def display_global_variable
        puts "#{$global_variable} access from class 'First'"
    end

    def class_variable
        @@class_variable += 1
        puts "value of class variable : #{@@class_variable}"
    end
end    

class Second
    def initialize(id,name)
        @id = id # id is a local variable
        @name = name # name is a local variable
    end

    def display_global_variable
        puts "#{$global_variable} access from class 'Second'"
    end

    def display_instance_variable
        puts "display value of instance variable id = #{@id}, name = #{@name} "
    end
end

#instantiate object
first = First.new
second = Second.new(1, "borey")

#Demonstrate on class variable
first.display_global_variable
second.display_global_variable
puts "\n"

#Demonstrate on class variable
first.class_variable
first.class_variable
puts "\n"

#Demonstrate on instance variable
second.display_instance_variable

Here’s the result after code is executed:

global variable access from class ‘First’
global variable access from class ‘Second’

value of class variable : 1
value of class variable : 2

display value of instance variable id = 1, name = borey

Explore posts in the same categories: Ruby & Rails

Tags:

You can comment below, or link to this permanent URL from your own site.

Comment: