在Ruby中定义新的逻辑运算符 [英] Defining a new logical operator in Ruby

查看:78
本文介绍了在Ruby中定义新的逻辑运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个无聊的白日梦,但是是否可以用一些巧妙的元编程技巧在Ruby中定义一个新的逻辑运算符?我想定义一个but运算符.

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.

例如,如果我想做某事,而x却不是y是真实的,我必须写类似的东西:

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

但是我想写

if x but not y

它应该与and完全相同,但是要由程序员明智地使用以提高代码的可读性.

It should work exactly the same as and but would be down to the programmer to use sensibly to increase the legibility of code.

推荐答案

如果不编辑Ruby解析器和源代码以及编译Ruby的新版本,您将无法进行.如果需要,可以使用以下丑陋的语法:

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.

这篇关于在Ruby中定义新的逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆