Accessing Hash Keys with user inputted variables, NoMethodError

本秂侑毒 提交于 2019-12-12 06:29:27

问题


I get this error message when trying to access a hash with user inputted variables: "undefined method `index' for nil:NilClass (NoMethodError)"

This should illustrate my problem a little better... once the string "n" is stored in a variable that variable can't access the hash anymore and returns nil. Why?

 [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    

回答1:


you simply need to convert line to a symbol: subway[line.to_sym]



来源:https://stackoverflow.com/questions/15725957/accessing-hash-keys-with-user-inputted-variables-nomethoderror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!