ruby - 如何将哈希实例化为对象(红宝石)
问题描述
我目前正在学习 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
解决方案
这是你的问题......你放了一个减号而不是一个等号
@description - arr[:description]
@description
因为像这样的实例变量nil
在初始化之前,你试图-
在一个nil
对象上运行方法,这准确地解释了你的错误消息。
推荐阅读
- javascript - Google Auth2 popup_closed_by_user
- javascript - 如何使用通用按钮+通过R闪亮中的javascript选择输入来更改轨迹n的情节图例状态
- javascript - Firebase 云函数返回 304 错误然后重启
- javascript - 检查 style="height: 0px"
- javascript - 您可以在代码中导入“devDependency”吗?
- javascript - 设置高度时缺少制表符滚动条
- django - 模型关系 Django
- r - 使用 dplyr/tidyverse 同时对多个变量进行多对 t 检验
- ms-access - 如何将 2 个文本框加到表单上的 3 个文本框中
- regex - NiFi ReplaceText:去除特定标签之间的所有 xml 标签