如何访问类的instance_variables以及为什么此方法调用return nil?

fab*_*bbb 0 ruby

class Human
  @core = "heart"

  def cardiovascular
    arr = ['heart','blood','lungs']
    core = @core
  end
end
Run Code Online (Sandbox Code Playgroud)

是我能够@core直接使用此方法访问的唯一方法:

Human.instance_variable_get(:@core)  #=> "heart"
Run Code Online (Sandbox Code Playgroud)

我的理解是,一个实例变量是从任何位置访问范围中的类.

我可以通过以下方式访问该方法:Human.new.cardiovascular我期望返回"heart"但是我得到的回报是nil

  1. 为什么我不能访问实例变量的Human.core还是Human.new.core?
  2. 为什么Human.new.cardiovascular回归nil?(不应该核心== @核心?)

更新

放入@core初始化块后,我在IRB中看到以下输出:

Human.new
=> #<Human:0x2f1f030 @core="heart">
Run Code Online (Sandbox Code Playgroud)

这是有意义的,因为它现在可用于整个类,但如何访问初始化块中的特定实例变量?意思是,我如何得到:在这种情况下@core不调用cardiovascular方法?

Ser*_*sev 5

做这个:

class Human
  def initialize
    @core = "heart"
  end

  def cardiovascular
    arr = ['heart','blood','lungs']
    core = @core
  end
end
Run Code Online (Sandbox Code Playgroud)

简而言之,您在类本身(也是一个对象)上设置实例变量,但您希望它在实例上.