Skip to content

Instantly share code, notes, and snippets.

@sumanmukherjee03
Created October 19, 2012 00:17
Show Gist options
  • Save sumanmukherjee03/3915546 to your computer and use it in GitHub Desktop.
Save sumanmukherjee03/3915546 to your computer and use it in GitHub Desktop.
Messing with class variables in ruby
# Execute this file as follows and compare the results in ruby 1.8.*:
#
# ruby class_var_ex.rb
# ruby class_var_ex.rb "include module"
# ruby class_var_ex.rb "include module" "include global"
# ruby "include global"
@@test = 9 if ARGV.last == "include global"
module X
@@test = 3
self.instance_variable_set('@test', 4)
def get_class_variable_from_module
puts "Class variable from module = " + @@test.to_s
end
def get_class_instance_variable_from_module
puts "Class instance variable from module = " + @test.to_s
end
end
class A
extend X
@@test = 1
self.instance_variable_set('@test', 2)
def self.get_class_variable
puts "Class variable = " + @@test.to_s
end
def self.get_class_instance_variable
puts "Class instance variable = " + @test.to_s
end
end
class B < A
B.send(:include, X) if ARGV.first == "include module"
@@test = 2
self.instance_variable_set('@test', 1)
end
def extended_modules_class_variable
puts "Module's class variable = " + X.send(:class_variable_get, '@@test').to_s
end
def extended_modules_class_instance_variable
puts "Module's class instance variable = " + X.instance_variable_get('@test').to_s
end
puts "Values from A >>>>>>>>>>>>>>"
A.get_class_variable_from_module
A.get_class_instance_variable_from_module
A.get_class_variable
A.get_class_instance_variable
puts "Values from B >>>>>>>>>>>>>>"
B.get_class_variable_from_module
B.get_class_instance_variable_from_module
B.get_class_variable
B.get_class_instance_variable
puts "Values from X >>>>>>>>>>>>>>"
extended_modules_class_variable
extended_modules_class_instance_variable
if ARGV.last == "include global"
puts "Values from Global scope >>>>>>>>>>>>>>"
puts "Class variable = " + @@test.to_s
end
@sumanmukherjee03
Copy link
Author

@mikong and @Erol thanks for the effort and help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment