【问题标题】:How to properly use file.json to objects on ruby?如何正确地将 file.json 用于 ruby​​ 上的对象?
【发布时间】:2019-04-05 03:17:10
【问题描述】:

我正在学习并做一些练习,但我一直坚持这个。

it 'Converts a JSON to an object of type recipe' do
recipe = Recipe.from_json('data/pudim.json')

expect(recipe.class).to eq Recipe
expect(recipe.title).to eq 'Pudim'
expect(recipe.description).to eq 'O melhor pudim da sua vida!'
expect(recipe.ingredients).to eq 'Leite condensado, ovos e leite'
expect(recipe.cook_time).to eq 80
expect(recipe.featured).to eq true
end

它要求您创建一个方法,以便它返回具有对象散列的 JSON 文件。

目前这是我所做的:

class Recipe
    require 'json'
    attr_accessor :title, :description, :ingredients, :cook_time, :featured

    def initialize(arr)
        @title = arr[:title]
        @description = arr[:description]
        @ingredients = arr[:ingredients]
        @cook_time = arr[:cook_time]
        @featured = arr[:featured]
    end

    def self.from_json(path)
        arquivo = File.read(path)
        recipe = JSON.parse(arquivo)
    end
end

rspec 说:

   Failure/Error: expect(recipe.class).to eq Recipe

   expected: Recipe
        got: Hash

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -Recipe
   +Hash

我尝试了许多不同的方法来将 JSON 解析为对象,但都做不到,而且 Ruby 文档有点混乱。 我的代码有什么问题? 另外,除了 ruby​​-doc.org 网站之外,还有什么地方可以查找 Ruby 文档?

【问题讨论】:

  • 您的类方法与任何 ruby​​ 方法一样,将返回在其中调用的最后一个方法。 JSON.parse(arquivo) 将返回一个哈希,因此您的测试将失败。您需要找到一种方法来返回您的 Recipe 类的实例以使该测试通过。
  • @lacostenycoder 在任何地方我都可以找到更多信息?任何与 JSON 相关的 ruby​​ 都有些混乱

标签: ruby class methods hash


【解决方案1】:

试试这个

def self.from_json(path)
  arquivo = File.read(path)
  Recipe.new JSON.parse(arquivo)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 2021-05-09
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多