-3

我应该如何考虑在任何方法定义之外@variable的块内声明?class << self看看这个脚本的最后一部分:

class VarDemo
  @@class_var_1 = "This is @@class_var_1"
  @class_i_var = "This is a @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 is @@class_var_2, defined within an instance method"
    @ivar_1 = ivar_1
    @ivar_2 = ivar_2
    VarDemo.class_i_var_2 = "class_i_var_2 defined through accessor on the class object"
  end

  def print_vars
    puts "from within an 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 the 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 be empty, as it doesn't exist in the instance"

    puts "self.class_i_var: #{self.class_i_var}"
  rescue Exception => ex
    puts "self.class_i_var is not defined in this scope (self is an instance)"
  end

  # open the class object
  class << self
    attr_accessor :class_i_var
    attr_accessor :class_i_var_2

    @what_about_this = "what would this be?"

    attr_accessor :what_about_this

    def print_what_about_this
      puts "@what_about_this: #{@what_about_this}" # is empty
      puts "VarDemo.what_about_this: #{VarDemo.what_about_this}" # is empty
    end
  end

end

是什么@what_about_this?它在哪里定义?它只是解释器让我做的事情,但没有任何实际用途吗?我以为它是在 上定义的Class,但似乎并非如此。

4

1 回答 1

2

class <<self实际上并没有打开自己的课程;它打开了自己的单例类。(在这里描述。)

class Foo
  class << self
    @bar = "baz"   # not really inside Class here.
  end
end

Foo.singleton_class.instance_eval { @bar }  #baz

Yehuda Katz 有一篇很好的文章描述了这里真正发生的事情。

于 2013-05-12T23:12:11.583 回答