Are Ruby Boolean Operator Methods Like Binary Operators?

I was wondering: && , and , || , or basic kernels are immutable functionality (for example, in other languages, for example: php), or are object methods like & <=> , but some kind of magic path

More on my traits of thoughts:

 [] & [10] # => [] [].&([10]) # => [] "aaa".& 10 # NoMethodError: undefined method `&' for "aaa":String 

Note that it says an undefined method

... of course you can do.

 true.& false # => false 

... but you cannot do:

 true.&& false # SyntaxError: 

so if it's possible to do

 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! 

exists (with some magic):

 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

+4
source share
2 answers

These are statements that cannot be defined (re):

  • & &, || (AND, OR)
  • .., ... (range)
  • ?: (triple)
  • the rescue
  • = (and ** =, && =, & =, * =, + =. - =, <<=, → =, || =, | =, ^ =)
  • identified?
  • not
  • and, or
  • if, if, while, until

Others, such as (incomplete list) !, ~, +, -, **, *, /,%, →, == ,! = are implemented as methods and can be overridden.

+3
source

David A. Black stated in his book:

[T] it is a conditional assignment operator ||= , as well as its rarely spotted cousin & =, both of which provide the same label as pseudo-operator methods, but based on operators, namely || and && which you cannot cancel.

Now, to understand the reason, look and read Why can't we override || and & ? and Operator Overloading .

+2
source

Source: https://habr.com/ru/post/1487034/


All Articles