Sha256: 3b9f2d3511b462245655d4e93945672425c4a3c5f1ccb7544b2cc3189931ebdf

Contents?: true

Size: 1.33 KB

Versions: 30

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Complex

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

  # Methods <tt>Complex#as_json</tt> and +Complex.json_create+ may be used
  # to serialize and deserialize a \Complex object;
  # see Marshal[https://docs.ruby-lang.org/en/master/Marshal.html].
  #
  # \Method <tt>Complex#as_json</tt> serializes +self+,
  # returning a 2-element hash representing +self+:
  #
  #   require 'json/add/complex'
  #   x = Complex(2).as_json      # => {"json_class"=>"Complex", "r"=>2, "i"=>0}
  #   y = Complex(2.0, 4).as_json # => {"json_class"=>"Complex", "r"=>2.0, "i"=>4}
  #
  # \Method +JSON.create+ deserializes such a hash, returning a \Complex object:
  #
  #   Complex.json_create(x) # => (2+0i)
  #   Complex.json_create(y) # => (2.0+4i)
  #
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'r'            => real,
      'i'            => imag,
    }
  end

  # Returns a JSON string representing +self+:
  #
  #   require 'json/add/complex'
  #   puts Complex(2).to_json
  #   puts Complex(2.0, 4).to_json
  #
  # Output:
  #
  #   {"json_class":"Complex","r":2,"i":0}
  #   {"json_class":"Complex","r":2.0,"i":4}
  #
  def to_json(*args)
    as_json.to_json(*args)
  end
end

Version data entries

30 entries across 30 versions & 5 rubygems

Version Path
es_cli-0.1.0 vendor/bundle/ruby/3.1.0/gems/json-2.9.1/lib/json/add/complex.rb
talon_one-7.0.0 .github/.example/vendor/bundle/ruby/3.3.0/gems/json-2.8.2/lib/json/add/complex.rb
json-2.9.1 lib/json/add/complex.rb
json-2.9.1-java lib/json/add/complex.rb
json-2.9.0 lib/json/add/complex.rb
json-2.9.0-java lib/json/add/complex.rb
cloudsmith-api-2.0.16 vendor/bundle/ruby/2.6.0/gems/json-2.7.6/lib/json/add/complex.rb
json-2.8.2-java lib/json/add/complex.rb
json-2.8.2 lib/json/add/complex.rb
json-2.8.1 lib/json/add/complex.rb
json-2.8.1-java lib/json/add/complex.rb
json-2.8.0 lib/json/add/complex.rb
json-2.8.0-java lib/json/add/complex.rb
json-2.8.0.alpha1 lib/json/add/complex.rb
json-2.7.6-java lib/json/add/complex.rb
json_pure-2.7.6 lib/json/add/complex.rb
json-2.7.6 lib/json/add/complex.rb
json_pure-2.7.5 lib/json/add/complex.rb
json-2.7.5 lib/json/add/complex.rb
json-2.7.5-java lib/json/add/complex.rb