From: "Jesús Gabriel y Galán" Date: 2011-08-04T22:42:50+09:00 Subject: Re: Creating Fields and Properties with Event Change Notifications On Thu, Aug 4, 2011 at 1:58 PM, Rubyist Rohit wrote: > ** Question from .NET perspective ** > > In a class I want to define fields and properties. I want this class to > implement any interface similar to INotifyPropertyChanged in .NET. I > want the public properties to send notifications to the objects that > subscribe to the property change events. > > So what I want is: > > -- private fields to initialize class constructor, > > -- public properties with link-up to any Interface like thing to send > property change notifications > > How to do this in Ruby? First of all, in Ruby the instance variables are always private. In order to access them you always use methods. Typically you use attr_reader, attr_writer and attr_accessor, which define the appropriate methods. For example: class A attr_accessor :value end will create the instance methods value and value= in class A. But you can create your own accessor methods that do whatever. In your case, the value= method would notify the listener of the change. For example: class A attr_reader :value # creates the getter method def value=(new_value) old_value = value @value = new_value observers.each {|observer| observer.property_changed(old_value, new_value)} end end Or something like that. How you populate the observers list is left as an exercise for the reader. Now, if you have many properties like that and you need to implement the same stuff for all of them, you can create a method to dynamically create those for you. Jesus.