# Instance Variable On-Change

**URL:** <https://www.ruby-forum.com/t/instance-variable-on-change/134600>\
**Category:** Ruby\
**Created:** [April 12, 2008, 6:30pm UTC](https://www.ruby-forum.com/t/instance-variable-on-change/134600 "2008-04-12T18:30:07Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![lazukars](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/eb9ed0/32.png) [@lazukars](https://www.ruby-forum.com/u/lazukars)\
**Post date:** [April 12, 2008, 6:30pm UTC](https://www.ruby-forum.com/t/instance-variable-on-change/134600/1 "2008-04-12T18:30:07Z")

</div>

I need to make a way to run a method when class’ instance variable  
changes from false to true and only run it once. But I have no idea how  
to do this.

Any ideas?

---

<div class="post-metadata">

**Author:** ![lazukars](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/eb9ed0/32.png) [@lazukars](https://www.ruby-forum.com/u/lazukars)\
**Post date:** [April 12, 2008, 7:18pm UTC](https://www.ruby-forum.com/t/instance-variable-on-change/134600/2 "2008-04-12T19:18:14Z")

</div>

Ryan L. wrote:

> I need to make a way to run a method when class’ instance variable  
> changes from false to true and only run it once. But I have no idea how  
> to do this.
> 
> Any ideas?

Check out the observer library.

---

<div class="post-metadata">

**Author:** ![lazukars](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/eb9ed0/32.png) [@lazukars](https://www.ruby-forum.com/u/lazukars)\
**Post date:** [April 12, 2008, 8:35pm UTC](https://www.ruby-forum.com/t/instance-variable-on-change/134600/3 "2008-04-12T20:35:08Z")

</div>

On Sun, Apr 13, 2008 at 02:17:37AM +0900, Tim H. wrote:

> Ryan L. wrote:
> 
> > I need to make a way to run a method when class’ instance variable  
> > changes from false to true and only run it once. But I have no idea how  
> > to do this.
> > 
> > Any ideas?
> 
> Check out the observer library.

why bother with observer if this can be nicely achieved with an  
appropriate setter? something like …

class SomeClass

def initialize  
@switch = false  
end

def switch=(value)  
on\_switch\_becomes\_true if !@switch && (@switch = value)  
end

def on\_switch\_becomes\_true  
# …  
end

end

g phil

---

<div class="post-metadata">

**Author:** ![lazukars](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/eb9ed0/32.png) [@lazukars](https://www.ruby-forum.com/u/lazukars)\
**Post date:** [April 12, 2008, 9:06pm UTC](https://www.ruby-forum.com/t/instance-variable-on-change/134600/4 "2008-04-12T21:06:14Z")

</div>

Philipp H. wrote:

> why bother with observer if this can be nicely achieved with an  
> appropriate setter? something like …

Good catch! I confess I assumed that the OP would not have asked if a  
plain setter method would do the trick.
