【问题标题】:How to instance hashes to objects (ruby)如何将哈希实例化为对象(红宝石)
【发布时间】:2019-04-05 00:52:55
【问题描述】:

我目前正在学习 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

【问题讨论】:

  • 错误信息说你正在尝试调用方法-,但是它不存在。在您的整个代码中,符号- 恰好一次 出现。看看那个事件。有意义吗?

标签: ruby class object methods


【解决方案1】:

这是你的问题...你用减号代替等号

@description - arr[:description]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多