Skip to content

Instantly share code, notes, and snippets.

@benjaminplee
Created November 20, 2011 19:09
Show Gist options
  • Save benjaminplee/1380717 to your computer and use it in GitHub Desktop.
Save benjaminplee/1380717 to your computer and use it in GitHub Desktop.
Playing with Ruby for QuickPiet interpreter
#! /usr/bin/env ruby
class Recorder
def push amt
puts "push: #{amt}"
end
def add
puts "add"
end
def macro name, &macro_def
puts "macro"
# first way; didn't work
# self.define_method name &macro_def
# second way; works
self.class.send(:define_method, name.to_s, &macro_def)
end
end
def quickpiet &script
recorder = Recorder.new
recorder.instance_eval &script
end
quickpiet do
macro plus2 do
push 2
add
end
push 2
plus2
end
@benjaminplee
Copy link
Author

I am looking for clean/simple way to expose quick piet commands w/o other ruby code and with a minimal added globally. Suggestions appreciated.

I was expecting this to output:
macro
push: 2
push: 2
add

instead I got

./piet.rb:27: undefined local variable or method plus2' for #<Recorder:0x1001692d8> (NameError) from ./piet.rb:23:ininstance_eval'
from ./piet.rb:23:in `quickpiet'
from ./piet.rb:26

@benjaminplee
Copy link
Author

Figured it out, error above was red herring b/c I didn't use a string or symbol for the macro method invocation.

next problem was accessing define_method correctly (As @adkron pointed out) since it is private to the class and not an instance method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment