Defining a new logical operator in Ruby

时光毁灭记忆、已成空白 提交于 2019-12-23 09:55:59

问题


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.


回答1:


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.




回答2:


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




回答3:


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 }


来源:https://stackoverflow.com/questions/8297645/defining-a-new-logical-operator-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!