0

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.

3
  • This is a pure-Ruby issue, so you shouldn't have a Rails tag. Commented Oct 17, 2019 at 4:54
  • I don't think Test2 is needed, as the question is perfectly clear without it. If anything it muddles the question. Note that there is no need for the keyword return in the last lines of a and b. If removed, true and false would be last expressions evaluated in each method, and therefore would be the respective return values. return does no harm, but the practice is to not use it when it is superfluous. Commented Oct 17, 2019 at 5:14
  • @CarySwoveland thanks for feedback on composition of the question. Commented Oct 17, 2019 at 20:54

1 Answer 1

1

In this example your method b never executes: && returns its first argument if it is falsy. Otherwise, it evaluates and returns its second argument. Since a.nil? evaluates to false the second expression never gets called.

Try this:

  def process 
    return if a && b
    puts @some
  end
Sign up to request clarification or add additional context in comments.

1 Comment

You might be more specific: a returns true and true.nil? #=> false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.