Ruby 错误 - 未定义局部变量或方法
Ruby Error - undefined local variable or method
我有一个 Ruby class,其中包含两种方法。第一种方法打开文件,第二种方法处理从文件中读取的数据。
请注意,这不是我正在处理的原始代码,而是用来演示我遇到的问题的代码。
class Example
def load_json(filepath)
require 'json'
file = File.read(path-to-file)
file_data = JSON.parse(file)
end
def read_data(tag)
load_json(tag)
#code to read and work with the data from file_data
end
end
当我尝试这样做时,出现以下错误:
`file_data': undefined local variable or method `file_data'
我完全是 Ruby 初学者。
将两个函数中的file_data
改为@file_data
,使其成为实例变量。没有 @ 它只是函数的局部,并且在函数 exits/returns.
时超出范围
class Example
def load_json(filepath)
require 'json'
file = File.read(path-to-file)
@file_data = JSON.parse(file)
end
def read_data(tag)
load_json(tag)
#code to read and work with the data from @file_data
end
end
我有一个 Ruby class,其中包含两种方法。第一种方法打开文件,第二种方法处理从文件中读取的数据。
请注意,这不是我正在处理的原始代码,而是用来演示我遇到的问题的代码。
class Example
def load_json(filepath)
require 'json'
file = File.read(path-to-file)
file_data = JSON.parse(file)
end
def read_data(tag)
load_json(tag)
#code to read and work with the data from file_data
end
end
当我尝试这样做时,出现以下错误:
`file_data': undefined local variable or method `file_data'
我完全是 Ruby 初学者。
将两个函数中的file_data
改为@file_data
,使其成为实例变量。没有 @ 它只是函数的局部,并且在函数 exits/returns.
class Example
def load_json(filepath)
require 'json'
file = File.read(path-to-file)
@file_data = JSON.parse(file)
end
def read_data(tag)
load_json(tag)
#code to read and work with the data from @file_data
end
end