Ruby 中的实例变量重置为 Nil

Instance Variable in Ruby Resetting as Nil

我的实例变量变回 nil,即使它是在调用的单独函数中设置的。

我已经尝试打印出实例变量值前后的值,并且看到它在哪里变为零。虽然这很令人费解。在下面附上一个例子(https://repl.it/repls/FirebrickPresentKeyboard):

class Test
  def process 
    return if a.nil? && b.nil?
    puts @some
  end

  def a
    @some = nil
    return true
  end

  def b
    @some = "abc"
    return false
  end

end

class Test2
  def process 
    return if c.nil?
    puts @hello
  end

  def c
    @hello = "hello"
    return true
  end
end

t = Test.new
t.process

t2 = Test2.new
t2.process

在测试 class 中,我希望 @some 打印 "abc",因为它是在 "b" 函数期间设置的。但是,它打印 nil。

在 Test2 class 中,我希望 @hello 打印 "hello",它确实如此。

在这个例子中,你的方法 b 永远不会执行: && returns 如果它是假的,它的第一个参数。否则,它计算 returns 它的第二个参数。由于 a.nil? 的计算结果为 false,因此永远不会调用第二个表达式。

试试这个:

  def process 
    return if a && b
    puts @some
  end