首页 > 解决方案 > 如何将哈希实例化为对象(红宝石)

问题描述

我目前正在学习 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: undefined method '-' for 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

标签: rubyclassobjectmethods

解决方案


这是你的问题......你放了一个减号而不是一个等号

@description - arr[:description]

@description因为像这样的实例变量nil在初始化之前,你试图-在一个nil对象上运行方法,这准确地解释了你的错误消息。


推荐阅读