This happens because of scoping. When you're inside of a method and you try to set a new variable like this:
class SomeData < ActiveRecord::Base
def set_active_flag(val)
active_flag = val
end
end
You are creating a brand new variable that lives inside of set_active_flag. As soon as that's done executing, it goes away, not altering self.active_flag
(the actual instance variable) in any way.
HOWEVER (this was a source of confusion for me): when you try to read an instance variable in ruby, like this:
class SomeData < ActiveRecord::Base
def whats_my_active_flag
puts active_flag
end
end
You'll actually get self.active_flag
(the actual instance variable) returned.
Here's why:
Ruby will do what it can to avoid returning nil
.
- It initially asks "does
active_flag
exist within the scope of whats_my_active_flag
?
- It searches and realizes the answer is "nope", so it jumps up one level, to the instance of SomeData
- It asks the same thing again: "does
active_flag
exist within this scope?
- The answer is "yup" and so it says "I got something for ya" and it returns that!
However, if you define active_flag
within the whats_my_active_flag
, and then ask for it, it goes through the steps again:
- It asks "does
active_flag
exist within the scope of whats_my_active_flag
?
- The answer is "yup", so it returns that value
In either case, it won't change the value of self.active_flag
unless you explicitly tell it to.
An easy way to describe this behavior is "it doesn't want to disappoint you" and return nil
-- so it does its best to find whatever it can.
At the same time, "it doesn't want to mess up data that you didn't intend to change" so it doesn't alter the instance variable itself.
Hope this helps!