Skip to content

Instantly share code, notes, and snippets.

@cdeszaq
Last active December 19, 2015 01:59
Show Gist options
  • Save cdeszaq/5880181 to your computer and use it in GitHub Desktop.
Save cdeszaq/5880181 to your computer and use it in GitHub Desktop.

TODO: Fill in the problem statement

// This can be used in lieu of changing the metaclass in the constructor,
// but affects _all_ classes, which can be a big overhead
// ExpandoMetaClass.enableGlobally()
class RobotDog {
String name
RobotDog() {
// Make the metaclass an expando so that we can cache behavior better
def mc = new ExpandoMetaClass(RobotDog,false,true)
mc.initialize()
this.metaClass = mc
}
def jump() {
println "$name jumps"
}
def jump(howHigh) {
println "$name jumps $howHigh feet into the air"
}
def jump(howHigh, times) {
println "$name jumps $howHigh feet into the air $times times"
}
def fetch(somethingToFetch) {
println "$name fetches the $somethingToFetch"
}
def chew(somethingToChewOn) {
println "$name chews on the $somethingToChewOn"
}
def chew(somethingToChewOn, howToChew) {
println "$name chews on the $somethingToChewOn in a $howToChew way"
}
def bark() {
println "$name barks"
}
def methodMissing(String commandName, args) {
// Create the method we'll call on subsequent commands
def cachedMethod = { Object[] cmArgs ->
// This is the default behavior when we don't know how to do something
println "$name stares at you blankly"
}
// Add it to the class so that it'll be called next time instead of doing all this
RobotDog.metaClass."$commandName" = cachedMethod // Adds it to the Class
metaClass."$commandName" = cachedMethod // Adds it to the object
// Call it, since that's what we were asked to do
return cachedMethod(args)
}
}
// Some instructions
def input = '''jump
bark
paw
paw
rollOver
rollOver
rollOver
rollOver
giveKisses
jump 5 2
fetch ball
fetch shoe
chew leg hard
'''
// Look, a new doggy!
def rob = new RobotDog(name: "Rob the Dog")
// Let's see what he can do...
input.eachLine {line ->
// Break the line into a list of pieces
def instruction = line.tokenize()
// Execute the line as a cons pair: Command at the head, followed by parameters
rob."${instruction.head()}"(*instruction.tail())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment