A complex number can be written as a literal like this:
3 + 2i # => (3+2i)
How is this syntactically distinguished from the case where receiver integer 3
receives the method +
with argument 2i
(which itself works as a literal for a complex number (0+2i)
)?
Short answer: it doesn't. The way it works is that the +
method of integer receives the imaginary unit and returns a Complex
. So in terms of literals you have the usual integer and floating point literals as well as imaginary number literal (e.g. 2i
) and by combining them you can construct complex values.
I guess the documentation is misleading and what appears to be literal is really method call. I made an experiment that confirms this:
class Integer
alias old_plus +
def +(*args)
puts 'called with complex' if args.first.class == Complex
old_plus(*args)
end
end
8+3i
# called with complex
# => (8+3i)
(9+2i)
# called with complex
# => (9+2i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With