class Complex

def self.json_create(object)

See #as_json.
def self.json_create(object)
  Complex(object['r'], object['i'])
end

def as_json(*)


Complex.json_create(y) # => (2.0+4i)
Complex.json_create(x) # => (2+0i)

\Method +JSON.create+ deserializes such a hash, returning a \Complex object:

y = Complex(2.0, 4).as_json # => {"json_class"=>"Complex", "r"=>2.0, "i"=>4}
x = Complex(2).as_json # => {"json_class"=>"Complex", "r"=>2, "i"=>0}
require 'json/add/complex'

returning a 2-element hash representing +self+:
\Method Complex#as_json serializes +self+,

see Marshal[https://docs.ruby-lang.org/en/master/Marshal.html].
to serialize and deserialize a \Complex object;
Methods Complex#as_json and +Complex.json_create+ may be used
def as_json(*)
  {
    JSON.create_id => self.class.name,
    'r'            => real,
    'i'            => imag,
  }
end

def to_json(*args)


{"json_class":"Complex","r":2.0,"i":4}
{"json_class":"Complex","r":2,"i":0}

Output:

puts Complex(2.0, 4).to_json
puts Complex(2).to_json
require 'json/add/complex'

Returns a JSON string representing +self+:
def to_json(*args)
  as_json.to_json(*args)
end