I was wondering, are &&
, and
, ||
, or
base core unchangeable functionalities (like in other languages eg: php) or are they object methods like &
<=>
but defined some magical way
More details on my trait of thoughts:
[] & [10]
# => []
[].&([10])
# => []
"aaa".& 10
# NoMethodError: undefined method `&' for "aaa":String
note it say undefined method
...of course you can do.
true.& false
# => false
...but you cannot do:
true.&& false
# SyntaxError:
so If it's possibility 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!
is there (with some magic) 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
# => SyntaxError: (irb):13: syntax error, unexpected keyword_end
thx
These are the operators that cannot be (re)defined:
The others, like (incomplete list) !, ~, +, -, **, *, /, %, >>, ==, != are implemented as methods and can be redefined.
David A. Black stated in his book:
[T]he conditional assignment operator
||=
, as well as its rarely spotted cousin &&=, both of which provide the same kind of shortcut as the pseudooperator methods but are based on operators, namely||
and&&
, which you can't override.
Now to get into the reason please Look and read Why can't we override
|| and
&& ?
and Operator Overloading
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.