Home > Software engineering >  Attempting to create a json object from ruby
Attempting to create a json object from ruby

Time:05-12

I'm attempting to create this string in Ruby.

{
quantity: 1,
discount_type: :dollar,
discount_amount: 0.01,
discount_message: 'this is my message',
}

By reading up on the classes I can see that I can initialize it like so:

class DiscountDisplay
    def initialize(quantity, type, amount, message)
        @quantity = quantity
        @discount_type = type
        @discount_amount = amount
        @discount_message = message
    end
end

f = DiscountDisplay.new( 1, :dollar, 0.01, 'this is my message' )

How can I actually create the json string? Not using the require 'json' others have indicated on some other answers.

CodePudding user response:

I would add a to_json method to the DiscountDisplay class like this:

class DiscountDisplay
  require 'json'

  def initialize(quantity, type, amount, message)
    # ...
  end

  def to_json
    JSON.generate(
      quantity: @quantity,
      discount_type: @discount_type,
      discount_amount: @discount_amount,
      discount_message: @discount_message,
    )
  end
end

And call it like this:

discount_display = DiscountDisplay.new(1, :dollar, 0.01, 'this is my message')
discount_display.to_json
#=> '{"quantity":1,"discount_type":"dollar","discount_amount":0.01,"discount_message":"this is my message"}'
  •  Tags:  
  • ruby
  • Related