ruby - Variables declared within `class << self` -
how should consider @variable
declared within class << self
block outside method definition? @ final part of script:
class vardemo @@class_var_1 = "this @@class_var_1" @class_i_var = "this @class_i_var" attr_accessor :ivar_1 attr_accessor :ivar_2 def initialize(ivar_1: "base_ivar_1", ivar_2: "base_ivar_2") @@class_var_2 = "this @@class_var_2, defined within instance method" @ivar_1 = ivar_1 @ivar_2 = ivar_2 vardemo.class_i_var_2 = "class_i_var_2 defined through accessor on class object" end def print_vars puts "from within instance method. here 'self' is: #{self}" # test instance variables puts "@ivar_1: #{@ivar_1}" puts "@ivar_2: #{@ivar_2}" puts "self.ivar_1: #{self.ivar_1}" puts "self.ivar_2: #{self.ivar_2}" puts "ivar_1: #{ivar_1}" puts "ivar_2: #{ivar_2}" # test class variables puts "@@class_var_1: #{@@class_var_1}" puts "@@class_var_2: #{@@class_var_2}" # test class instance variables (ivars on class object) puts "vardemo.class_i_var: #{vardemo.class_i_var}" puts "vardemo.class_i_var_2: #{vardemo.class_i_var_2}" puts "@class_i_var: #{@class_i_var} (should empty, doesn't exist in instance" puts "self.class_i_var: #{self.class_i_var}" rescue exception => ex puts "self.class_i_var not defined in scope (self instance)" end # open class object class << self attr_accessor :class_i_var attr_accessor :class_i_var_2 @what_about_this = "what be?" attr_accessor :what_about_this def print_what_about_this puts "@what_about_this: #{@what_about_this}" # empty puts "vardemo.what_about_this: #{vardemo.what_about_this}" # empty end end end
what @what_about_this
? defined? interpreter lets me do, without practical use? thought defined on class
, doesn't appear case.
the class <<self
doesn't open self's class; opens self's singleton class. (described here.)
class foo class << self @bar = "baz" # not inside class here. end end foo.singleton_class.instance_eval { @bar } #baz
yehuda katz has article describes what's going on here.
Comments
Post a Comment