Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex number literal

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))?

like image 431
sawa Avatar asked Dec 24 '22 00:12

sawa


2 Answers

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.

like image 184
Svetlin Simonyan Avatar answered Jan 05 '23 02:01

Svetlin Simonyan


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)
like image 32
Marek Lipka Avatar answered Jan 05 '23 01:01

Marek Lipka