Mike Austin's Blog

Friday, November 24, 2006

The joy of dynamic dispatching

I like to write as little code as possible. One way to do that is to use method names (symbols), and use send() to dispatch on those values:
class Event
def initialize( type, args )
@type, @args = type, args
end
end

def send_event( event )
send( event.type, *event.args )
end

def mouse_down( origin )
puts 'mouse_down()'
end

view.send_event( MouseEvent.new( :mouse_down, [50, 50] ) )
Nothing big, but using it often can eliminate a lot of if statements.