Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a new logical operator in Ruby

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.

like image 940
Russell Avatar asked Nov 28 '11 14:11

Russell


2 Answers

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.

like image 163
Guilherme Bernal Avatar answered Nov 14 '22 22:11

Guilherme Bernal


If you really want to do this, try editing parse.y and recompiling Ruby. That's where Ruby's syntax is defined.

like image 31
Andrew Grimm Avatar answered Nov 14 '22 21:11

Andrew Grimm