【发布时间】:2015-12-26 14:02:24
【问题描述】:
您好,我创建了一个由 JSON 文件组成的小型 ruby 项目。我将 JSON 数据存储到哈希键中。并编写了一种方法来使用用户输入访问哈希键中存在的数据。但是当我尝试发送使用用户输入时,我收到了这个错误
how_many_ingredients': undefined methodkeys' for nil:NilClass (NoMethodError)
我发现这个链接有同样的问题,并尝试了这个解决方案,但我仍然遇到同样的错误 Accessing Hash Keys with user inputted variables, NoMethodError
所有方法都写到的文件一
require 'json'
class Methods
attr_accessor :name, :text
def initilize(name)
@name = name
@text = text
end
def how_many_ingredients(text)
puts 'text'
file = File.read('a.json')
hash = JSON.parse(file)
#puts hash['recipes']['pizza'].keys
puts hash['recipes'][text].keys
end
end
访问how_Many_ingredients方法的文件2,我可以看到变量被传递给了那个方法
require './1'
class Hello < Methods
person = Methods.new
person.test
puts "enter recipie"
person.name
str = gets
person.how_many_ingredients str
end
【问题讨论】:
标签: ruby-on-rails ruby