Paul Brannan
12/28/2007 6:37:00 PM
On Sat, Dec 29, 2007 at 01:21:04AM +0900, Giles Bowkett wrote:
> I'm writing some code which needs to do something unusual when it
> encounters an if, an else, or an end.
>
> >> def if
> >> "asdf"
> >> end
> => nil
> >> if
> ?> true
> >> end
> => nil
>
> The ?> line comes up because if appears to not be a method but an
> operator or something similar, so my override does nada.
>
> Is there any way to do this? It looks as if I have to either rethink
> my strategy or write some kind of parser.
It works if you call #if on an object. I do something like this in
ruby-libjit:
class Function
def if(condition, &block)
# append code to:
# - if the condition is true, execute the code appended by the
# block
# - if the condition is false, branch to the end label
block.call
return If.new(self)
end
class If
def initialize(function)
@function = function
end
def end
# append the end label here
end
end
end
so I can write something like:
Function.compile do |f|
f.if(<condition>) {
# true case
} .else {
# false case
} .end
end
(I've omitted the code for #else for simplicity, because it really makes
the code complicated)
Paul