我是Rubywan,所以我还是新手。任何建议都会非常有帮助!目前正致力于找出方法和哈希。我正在尝试访问名为school的Hash,但不断提出NameError。更具体地说,这是错误(后面是试图访问哈希的方法):
test.rb:19:in `student_grade': undefined local variable or method `school' for main:Object (NameError).
def student_grade(student_name)
student = school[:students].select do |student|
if student[:name] == student_name
student_grade = student[:grade]
puts student_grade
else
puts "Student doesn't exist!"
end
end
end
答案 0 :(得分:2)
school
局部变量是在方法范围之外创建的(方法有自己的局部变量范围)。因此,您无法在方法student_grade
内访问它。作为一个例子,见下文:
hsh = {:a => 1}
def foo
hsh
end
foo
# undefined local variable or method `hsh' for main:Object (NameError)
要访问您必须按以下方式传递它:
hsh = {:a => 1}
def foo(hsh)
hsh
end
foo(hsh) # => {:a=>1}
要阅读有关局部变量范围的更多信息,请参阅此处:Scope of local variable