Ruby的逻辑运算符是否像二进制运算符一样是方法?

4
我在想,&&and||or是基础核心不可改变的功能(就像其他语言如php中的那样),还是像& <=>这样的对象方法,但是以某种神奇的方式定义? 关于我的思考方式的更多细节:
[] & [10]
# => []

[].&([10])
# => []

"aaa".& 10
# NoMethodError: undefined method `&' for "aaa":String

注意:它说未定义的方法

...当然你可以做到。

true.& false
# => false

但是你不能做到以下几点:

true.&& false
# SyntaxError:

所以如果有这个可能性

class String
  # monkey patch. If you googled this don't use this in real world, use ruby mixins insted
  def &(right_side)
    # do something meaningfull
    right_side
  end
end

"aaa".& 10
# => 10     # ta-da!

有没有(通过某些魔法)可能做到以下事情:
class String
  # monkey patch. If you googled this don't use this in real world, use ruby mixins insted
  def &&(right side)
    # do something meaningfull
    right side
  end
end
# => SyntaxError: (irb):13: syntax error, unexpected keyword_end

thx

enter image description here


可能是 为什么不能重载 `||` 和 `&&`? 的重复。 - undur_gongor
2个回答

3

以下是不能被(重新)定义的运算符:

  • &&, || (AND, OR)
  • .., ... (范围)
  • ?: (三元)
  • rescue
  • = (和 **=, &&=, &=, *=, +=. -=, <<=, >>= , ||=, |=, ^=)
  • defined?
  • not
  • and, or
  • if, unless, while, until

其他运算符,例如(不完整列表)!,~,+,-,**,*,/,%,>>,==,!= 被实现为方法,可以被重新定义。


1
classmoduledef可以被重新定义吗?raise呢? - Denis de Bernardy
1
@Denis,这些在《Ruby编程语言》第4.6章中并未列为运算符。但它们是关键字。 - steenslag

2

David A. Black在他的书中提到:

条件赋值运算符||=及其很少见的表亲&&=,它们都提供了与伪操作方法相同的快捷方式,但是基于运算符||&&,这些运算符无法被覆盖。

现在,请查看并阅读为什么不能覆盖||&&以及运算符重载以了解原因。


谢谢你的有趣阅读,但我将接受steenslag的答案,因为它更加详细。 - equivalent8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接