0

I'm a Rubywan, so I'm still new to this. Any advice would be extremely helpful! Currently working on figuring out methods and hashes. I'm trying to access the Hash named school, but keep coming up with a NameError. More specifically, this is the error (followed by the method that's trying to access the Hash):

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
4

1 回答 1

1

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

于 2013-09-21T15:09:01.943 回答