mercredi 16 octobre 2019

Instance Variable in Ruby Resetting as Nil

My instance variables gets turned back to nil, even though it was set in a separate function that is called.

I've tried printing out before and after values for the instance variable, and have seen where it turns to nil. It's quite puzzling though. Attaching an example (https://repl.it/repls/FirebrickPresentKeyboard) also below:

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

In the Test class, I expect @some to print "abc" since it is set during the "b" function. However, it prints nil.

In the Test2 class, I expect @hello to print "hello" and it certainly does.

Aucun commentaire:

Enregistrer un commentaire