Skip to content
instance method

Kernel#Complex

(::_ToC complex_like, ?exception: true) -> ::Complex
(::_ToC complex_like, exception: bool) -> ::Complex?
(::Numeric | ::String real, ?::Numeric | ::String imag, ?exception: true) -> ::Complex
(::Numeric | ::String real, ?::Numeric | ::String imag, exception: bool) -> ::Complex?
(untyped, ?untyped, ?exception: bool) -> ::Complex?
Complex(real, imag = 0, exception: true) → complex or nil
Complex(s, exception: true) → complex or nil

Returns a new Complex object if the arguments are valid; otherwise raises an exception if exception is true; otherwise returns nil.

With Numeric arguments real and imag, returns Complex.rect(real, imag) if the arguments are valid.

With string argument s, returns a new Complex object if the argument is valid; the string may have:

  • One or two numeric substrings, each of which specifies a Complex, Float, Integer, Numeric, or Rational value, specifying rectangular coordinates:

    • Sign-separated real and imaginary numeric substrings (with trailing character 'i'):

      Example
      Complex('1+2i')  # => (1+2i)
      Complex('+1+2i') # => (1+2i)
      Complex('+1-2i') # => (1-2i)
      Complex('-1+2i') # => (-1+2i)
      Complex('-1-2i') # => (-1-2i)
      
    • Real-only numeric string (without trailing character 'i'):

      Example
      Complex('1')  # => (1+0i)
      Complex('+1') # => (1+0i)
      Complex('-1') # => (-1+0i)
      
    • Imaginary-only numeric string (with trailing character 'i'):

      Example
      Complex('1i')  # => (0+1i)
      Complex('+1i') # => (0+1i)
      Complex('-1i') # => (0-1i)
      
  • At-sign separated real and imaginary rational substrings, each of which specifies a Rational value, specifying polar coordinates:

    Example
    Complex('1/2@3/4')   # => (0.36584443443691045+0.34081938001166706i)
    Complex('+1/2@+3/4') # => (0.36584443443691045+0.34081938001166706i)
    Complex('+1/2@-3/4') # => (0.36584443443691045-0.34081938001166706i)
    Complex('-1/2@+3/4') # => (-0.36584443443691045-0.34081938001166706i)
    Complex('-1/2@-3/4') # => (-0.36584443443691045+0.34081938001166706i)
    
See also #clone #__dir__ #class #eval also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0