P
Phil Tomson
As part of a DSL, I'd like to define my own if...else...end syntax (it's
either that or figure out how to use ripper and actually parse Ruby code - I'd
prefer to avoid that if possible).
Of course, first off you cant define an 'if' or 'else' method:
def if
...
end #won't work because if is 'reserved'
so I'll have to define an if? method instead:
def if?(boolean, &b)
if boolean
b.call
end
end
Seems pretty straightforward... but then assuming you could define an 'else?'
method, how would you define things so you could do:
if?(a==10){ puts "a is 10"} else? { puts "a is not 10"} #this
without '.'s as in:
if?(a==10){puts "a is 10}.else?{ puts "a is not 10 } #don't want this
Is it possible?
Of course the 'if?' method would have to change as well to accomodate the
'else?'
Maybe something like:
def if?(boolean, &b)
if boolean
b.call
end
boolean
end
with 'else?' being defined on TrueClass, FalseClass, NilClass:
class FalseClass
def else?(&b)
b.call
end
end
class TrueClass
def else?(&b)
#do nothing
end
end
class NilClass
def else?(&b)
b.call
end
end
but this still requires the '.' to work:
a=10
if?(a==10){puts "a is ten"}.else?{puts "a is not ten"} #=> a is ten
a=5
if?(a==10){puts "a is ten"}.else?{puts "a is not ten"} #=> a is not ten
Bonus points: Any way to get rid of the '.'s _and_ also allow:
if?(a==10){
puts "a is ten"
}
else? {
puts "a is not ten"
}
???
Phil
either that or figure out how to use ripper and actually parse Ruby code - I'd
prefer to avoid that if possible).
Of course, first off you cant define an 'if' or 'else' method:
def if
...
end #won't work because if is 'reserved'
so I'll have to define an if? method instead:
def if?(boolean, &b)
if boolean
b.call
end
end
Seems pretty straightforward... but then assuming you could define an 'else?'
method, how would you define things so you could do:
if?(a==10){ puts "a is 10"} else? { puts "a is not 10"} #this
without '.'s as in:
if?(a==10){puts "a is 10}.else?{ puts "a is not 10 } #don't want this
Is it possible?
Of course the 'if?' method would have to change as well to accomodate the
'else?'
Maybe something like:
def if?(boolean, &b)
if boolean
b.call
end
boolean
end
with 'else?' being defined on TrueClass, FalseClass, NilClass:
class FalseClass
def else?(&b)
b.call
end
end
class TrueClass
def else?(&b)
#do nothing
end
end
class NilClass
def else?(&b)
b.call
end
end
but this still requires the '.' to work:
a=10
if?(a==10){puts "a is ten"}.else?{puts "a is not ten"} #=> a is ten
a=5
if?(a==10){puts "a is ten"}.else?{puts "a is not ten"} #=> a is not ten
Bonus points: Any way to get rid of the '.'s _and_ also allow:
if?(a==10){
puts "a is ten"
}
else? {
puts "a is not ten"
}
???
Phil