Variables in Ruby

 Uncategorized  Add comments
Mar 192009
 

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

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2012 Programming & technology Suffusion theme by Sayontan Sinha