Very much an idle day-dream this but is it possible with some neat meta-programming trick to define a new logical operator in Ruby? I'd like to define a but
operator.
For example, if I want to do something if x
but not y
is true I have to write something like:
if x and not y
But I would like to write
if x but not y
It should work exactly the same as and
but would be down to the programmer to use sensibly to increase the legibility of code.
Without editing the Ruby parser and sources and compiling a new version of Ruby, you can't. If you want, you can use this ugly syntax:
class Object
def but(other)
self and other
end
end
x.but (not y)
Note that you can't remove the parentheses or the space in this snippet. It will also shadow the functionality of the code to someone else reading your code. Don't do it.
If you really want to do this, try editing parse.y and recompiling Ruby. That's where Ruby's syntax is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With