Mike Austin's Blog

Sunday, October 28, 2007

Fun with runtime method names

Executing arbitrary method names makes code so much simpler. You don't have to branch or use lookup tables or any of that. Here's the heart of a simple calculator:
class Calculator
def initialize()
[...]
button_1.action = Action.new( self, :number_pressed, [1] )
button_2.action = Action.new( self, :number_pressed, [2] )
button_add.action = Action.new( self, :operator_pressed, [:+] )
end

def number_pressed( number )
@input += number.to_s
puts @input
end

def operator_pressed( operator )
@value = @value.send( @last_op, @input.to_f )
@input = ''
@last_op = operator
puts @value
end
end