使用用户输入的变量访问哈希键,NoMethodError [英] Accessing Hash Keys with user inputted variables, NoMethodError
本文介绍了使用用户输入的变量访问哈希键,NoMethodError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试使用用户输入的变量访问哈希时收到此错误消息:未定义方法 `index' for nil:NilClass (NoMethodError)"
I get this error message when trying to access a hash with user inputted variables: "undefined method `index' for nil:NilClass (NoMethodError)"
这应该能更好地说明我的问题……一旦字符串n"存储在一个变量中,该变量就无法再访问散列并返回 nil.为什么?
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
推荐答案
你只需要将线转换为符号:subway[line.to_sym]
you simply need to convert line to a symbol: subway[line.to_sym]
这篇关于使用用户输入的变量访问哈希键,NoMethodError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文