4

I was wondering, are &&, and, ||, or base core unchangeable functionalities (like in other languages e.g.: 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

enter image description here

1

2 Answers 2

3

These are the operators that cannot be (re)defined:

  • &&, || (AND, OR)
  • .., ... (range)
  • ?: (ternary)
  • rescue
  • = (and **=, &&=, &=, *=, +=. -=, <<=, >>= , ||=, |=, ^=)
  • defined?
  • not
  • and, or
  • if, unless, while, until

The others, like (incomplete list) !, ~, +, -, **, *, /, %, >>, ==, != are implemented as methods and can be redefined.

2
  • 1
    class, module and def can be redefined? raise? Jun 19, 2013 at 12:49
  • 1
    @Denis Those are not listed as operators in chapter 4.6 of The Ruby Programming Language. They are keywords however.
    – steenslag
    Jun 19, 2013 at 13:09
2

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.

1
  • thank you for this interesting to read, but I'll have to accept steenslag answer as it's more descriptive. Jun 19, 2013 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.