正在尝试从 ruby 创建 json 对象

Attempting to create a json object from ruby

我正在尝试在 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' 其他人在其他一些答案中指出。

我会像这样向 DiscountDisplay class 添加一个 to_json 方法:

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"}'