我正在嘗試在 Ruby 中創建這個字串。
{
quantity: 1,
discount_type: :dollar,
discount_amount: 0.01,
discount_message: 'this is my message',
}
通過閱讀類,我可以看到我可以像這樣初始化它:
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' )
我如何才能真正創建 json 字串?不使用其他人在其他答案中指出的需要“json”。
uj5u.com熱心網友回復:
我會像這樣to_json向DiscountDisplay類添加一個方法:
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
并這樣稱呼它:
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"}'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474205.html
標籤:红宝石
