Defining a new logical operator in Ruby

A very simple dream day, but is it possible to define a new logical operator in Ruby using a neat metaprogram trick? I would like to define a but statement.

For example, if I want to do something, if x , but not y true, I should write something like:

 if x and not y 

But I would like to write

 if x but not y 

It should work just like and , but for the programmer to use it wisely to increase the readability of the code.

+4
source share
3 answers

Without editing the parsing and Ruby sources and compiling a new version of Ruby, you cannot. If you want, you can use this ugly syntax:

 class Object def but(other) self and other end end x.but (not y) 

Please note that you cannot remove parentheses or space in this snippet. It will also hide code functionality for someone else reading your code. Do not do that.

+6
source

If you really want to, try editing parse.y and recompiling Ruby. This means that Ruby syntax is defined.

+2
source

As others have already pointed out, you cannot define your own operators in Ruby. The set of operators is predefined and fixed. All you can do is influence the semantics of some of the existing operators (namely, those that are translated into sending messages) by responding to the corresponding messages.

But of course, you can easily implement the but method:

 class Object def but self && yield end end Object.new.but { not true } 
0
source

Source: https://habr.com/ru/post/1383441/


All Articles