Defining a new logical operator in Ruby

2019-06-27 14:15发布

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.

3条回答
手持菜刀,她持情操
2楼-- · 2019-06-27 14:29

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.

查看更多
The star\"
3楼-- · 2019-06-27 14:30

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

查看更多
来,给爷笑一个
4楼-- · 2019-06-27 14:42

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 the ones that get translated into message sends) by responding to the appropriate messages.

But of course, you can implement a but method quite easily:

class Object
  def but
    self && yield
  end
end

Object.new.but { not true }
查看更多
登录 后发表回答