如何实例化对对象的哈希(红宝石)

时间:2018-10-31 19:09:10

标签: ruby class object methods

我目前正在学习Ruby,现在正在练习它的第三天,但是在类和对象方面遇到了麻烦。

escribe Recipe do
it 'Instance an object of type recipe' do
recipe = Recipe.new(title: 'Feijoada',
                    description: 'Você nunca comeu uma receita igual',
                    ingredients: 'Feijão e Carnes',
                    cook_time: 80,
                    featured: true)

expect(recipe.class).to eq Recipe
expect(recipe.title).to eq 'Feijoada'
expect(recipe.description).to eq 'Você nunca comeu uma receita igual'
expect(recipe.ingredients).to eq 'Feijão e Carnes'
expect(recipe.cook_time).to eq 80
expect(recipe.featured).to eq true
end

如何正确地初始化每个散列,使其在返回时可以读取?运行rspec会给我“ NoMethodError:nil:NilClass的未定义方法'-'”

这是我当前的班级代码:

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

1 个答案:

答案 0 :(得分:1)

这是您的问题...您放减号而不是等距

@description - arr[:description]

由于@description之类的实例变量在初始化之前一直nil,因此您尝试在-对象上运行方法nil,该对象准确地解释了错误消息。 / p>