Last active
August 29, 2015 14:05
-
-
Save tapickell/5e658bf1acda2d95b517 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OPERANDS = {zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9} | |
OPERATIONS = {plus: :+, minus: :-, times: :*, divided_by: :/} | |
def self.method_missing(message, *args) | |
if is_target_message? message | |
process_message message, *args | |
else | |
super | |
end | |
end | |
def process_message message, *args | |
call_operand(message, *args) || call_operation(message, *args) | |
end | |
def call_operand message, *args | |
return false unless is_operand? message | |
return OPERANDS[message] if args.empty? | |
OPERANDS[message].send args.first[0], args.first[1].to_f | |
end | |
def call_operation message, *args | |
[OPERATIONS[message], *args] | |
end | |
def is_operand? message | |
OPERANDS.has_key? message | |
end | |
def is_target_message? message | |
OPERANDS.merge(OPERATIONS).has_key? message | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not as small as some solutions that were just defining methods on the Object class but I prefer to lean towards a practical solution that would be useable in production. You would never money patch Object like that for a real world application.