Hi folks.
I tried to reproduce a Mixin example that is include in the Pick Axe
book, here’s the code:
module Observable
def observers
@observer_list ||= []
end
def add_observer( obj )
----???
observers << obj
end
def print_observers
@observer_list.each{ |i| puts i }
end
end
def notify_observers
# ----???
observers.each {|o| o.update }
end
class TelescopeScheduler
include Observable
def initialize
@observer_list = [ ]
end
def add_viewer( viewer )
@observer_list << viewer
end
end
visor1 = “Carlos”
visor2 = “Ana”
my_telescope = TelescopeScheduler.new
my_telescope.add_viewer(visor1)
my_telescope.add_viewer(visor2)
my_telescope.print_observers
It works great however while reviewing the code I noticed a couple of
situations that I really don’t understand:
- Is it possible to invoke a method with a “<<” notation ?
What I mean is that inside the “add_observer” method I’m calling
observers using << instead of parenthesis:
def add_observer( obj )
observers << obj
end
On the other side while reviewing the “observers” method, I noticed that
there is no parameter in its definition:
def observers
@observer_list ||= []
end
Is this valid ? ( I suppose it is because it works ), but how does this
works ?
- Same situation happens in the “notify_observers” method, in it I can
invoke “observers.each” although it is not defined anywhere. Why can I
do that?
Any help with this questions would be very appreciated.
Best Regards
Carlos