Ruby 使用用户输入的变量NoMethodError访问哈希键

Ruby 使用用户输入的变量NoMethodError访问哈希键,ruby,variables,nomethoderror,Ruby,Variables,Nomethoderror,我在尝试使用用户输入的变量访问哈希时收到此错误消息:“nil:NilClass(NoMethodError)的未定义方法'index'” 这应该能更好地说明我的问题。。。一旦字符串“n”存储在变量中,该变量就不能再访问散列,并返回nil。为什么? [6] pry(main)> line = "n" => "n" [7] pry(main)> subway[:line] => nil [8] pry(main)> subway[:"n"] => ["times

我在尝试使用用户输入的变量访问哈希时收到此错误消息:“nil:NilClass(NoMethodError)的未定义方法'index'”

这应该能更好地说明我的问题。。。一旦字符串“n”存储在变量中,该变量就不能再访问散列,并返回nil。为什么?

 [6] pry(main)> line = "n"
=> "n"
[7] pry(main)> subway[:line]
=> nil
[8] pry(main)> subway[:"n"]
=> ["timessquare", "34th", "28th", "23rd", "unionsquare", "8th"]
[9] pry(main)> line
=> "n"

This is the .rb file



n = ["timessquare", "34th","28th","23rd","unionsquare","8th"]
l = ["8th", "6th", "unionsquare","3rd","1st"]
six = ["grandcentral","33rd","28th","23rd","unionsquare","astorplace"]

subway = {:n=>n, :l=> l, :six=>six}


puts "Where would you like to go?"
destination = gets.strip.chomp.downcase.delete(" ")



puts "What line is that on?"
endline = gets.strip.chomp.downcase.delete(" ")


puts "What station will you be departing from?"
location = gets.strip.chomp.downcase.delete(" ")


puts "What line is that on?"
startline = gets.strip.chomp.downcase.delete(" ")


if startline == endline
    puts (startline.index(destination)-startline.index(location)).abs
else
    puts "You have #{(subway[:startline].index(location) - subway[:startline].index("unionsquare")).abs} stops until transfer"
    puts "After you have #{(subway[:endline].index(destination) - subway[:endline]index("unionsquare")).abs} until your destination"    
end    

您只需将线条转换为符号:
subway[line.to_sym]