Reputation: 3320
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.
Upvotes: 0
Views: 29
Reputation: 107117
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"}'
Upvotes: 2