Skip to content

Instantly share code, notes, and snippets.

@igrep
Created April 8, 2012 03:13
Show Gist options
  • Select an option

  • Save igrep/2334211 to your computer and use it in GitHub Desktop.

Select an option

Save igrep/2334211 to your computer and use it in GitHub Desktop.
Notes about class variable in Ruby
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
$VERBOSE = true
def new_section
puts '-' * 80
end
# Can a class variable be accessed from the class methods?
class Hoge
@@a = "in #{self}"
def a; @@a; end
def a= val; @@a = val; end
class << self
def a; @@a; end
def a= val; @@a = val; end
end
end
puts "Hoge.a: #{Hoge.a.inspect}"
Hoge.a = "from class method"
puts "assigned Hoge.a"
puts "Hoge.a: #{Hoge.a.inspect}"
new_section
hoge = Hoge.new
puts "hoge.a: #{hoge.a.inspect}"
hoge.a = "from instance method"
puts "assigned hoge.a"
puts "hoge.a: #{hoge.a.inspect}"
puts "Hoge.a: #{Hoge.a.inspect}"
class Hoge
puts "@@a in #{self}: #{@@a.inspect}"
end
new_section
def Hoge.b; @@b; end
# @@b is treated as a class variable of Object!
def Hoge.b= val; @@b = val; end
puts 'assigned Hoge.b'
Hoge.b = "from class method defined in the top level"
class Object
puts "@@b in #{self}: #{@@b.inspect}"
end
class Hoge
puts "@@b in #{self}: #{@@b}"
end
new_section
class Hoge
@@b = "in #{self} B"
@@c = "in #{self} C"
puts "assigned @@b and @@c in #{self}"
end
class Object
puts "@@b in #{self}: #{@@b.inspect}"
puts "@@c in #{self}: UNDEFINED!" unless class_variable_defined? :@@c
end
new_section
class Object
@@b = "in #{self} B"
@@c = "in #{self} C"
puts "assigned @@b and @@c in #{self}"
end
class Hoge
puts "@@b in #{self}: #{@@b.inspect}"
puts "@@c in #{self}: #{@@c.inspect}"
end
Hoge.a: "in Hoge"
assigned Hoge.a
Hoge.a: "from class method"
--------------------------------------------------------------------------------
hoge.a: "from class method"
assigned hoge.a
hoge.a: "from instance method"
Hoge.a: "from instance method"
@@a in Hoge: "from instance method"
--------------------------------------------------------------------------------
assigned Hoge.b
@@b in Object: "from class method defined in the top level"
@@b in Hoge: from class method defined in the top level
--------------------------------------------------------------------------------
assigned @@b and @@c in Hoge
@@b in Object: "in Hoge B"
@@c in Object: UNDEFINED!
--------------------------------------------------------------------------------
assigned @@b and @@c in Object
@@b in Hoge: "in Object B"
@@c in Hoge: "in Hoge C"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment