尝试从Ruby中的哈希数组初始化键
他在寻找答案,但没有走多远。下面是我要做的:我有一个解析器类,它返回一个散列数组。我正在尝试将数据导入另一个类,并将键设置为实例变量,然后开始做一些很酷的事情。在尝试建立实例变量时,我一直看到“没有将符号隐式转换为整数(TypeError)”。我错过了什么尝试从Ruby中的哈希数组初始化键,ruby,arrays,class,hash,Ruby,Arrays,Class,Hash,他在寻找答案,但没有走多远。下面是我要做的:我有一个解析器类,它返回一个散列数组。我正在尝试将数据导入另一个类,并将键设置为实例变量,然后开始做一些很酷的事情。在尝试建立实例变量时,我一直看到“没有将符号隐式转换为整数(TypeError)”。我错过了什么 class Parser attr_accessor :recipe_array def initialize(filename) @filename = filename @zip_array = [] ru
class Parser
attr_accessor :recipe_array
def initialize(filename)
@filename = filename
@zip_array = []
run
end
def run
replace_ingredient_commas
make_recipe_array
parse_for_zip
make_hash
get_args
end
def replace_ingredient_commas
@recipe_array = File.read(@filename).gsub!((/,\ /),'. ')
end
def make_recipe_array
@recipe_array = @recipe_array.split(",")
end
def parse_for_zip
@recipe_headers = @recipe_array.shift(5)
3.times do
@zip_array.push(@recipe_array.shift(4))
end
# unable to resolve disappearing id numbers with regexp or with the split. Fixing it here. Refact opp.
counter = 1
@zip_array.each do |recipe|
recipe.unshift(counter)
counter += 1
end
end
def make_hash
# @recipe_hash = Hash.new
@args = @zip_array.map do |recipe|
Hash[@recipe_headers.zip(recipe)]
end
p @args
end
def get_args
@args
end
end
class Bistro
attr_reader :id, :name, :description, :ingredients, :directions
def initialize(args ={})
@id = args[:id]
@name = args[:name]
@description = args[:description]
@ingredients = args[:ingredients]
@directions = args[:directions]
end
end
# TESTS
parsed_info = Parser.new("recipes.csv")
bistro_test = Bistro.new(parsed_info.get_args)
parsed_info.get_args
是一个数组,而不是散列Array#[]
只接受整数,因此args[:id]
是一个无效的调用。虽然包含完整的代码很有帮助,但在提问时创建一个更有用的参数。实际上,我无法重现您的错误,因为我没有recipes.csv
文件来运行它。