【发布时间】:2020-04-13 02:26:01
【问题描述】:
我正在学习哈希,但不知道为什么它不会打印最后一行 (capital_city)。
more_states = {
"Oklahoma": "OK",
"Texas": "TX",
"Colorado": "CO",
"Kansas": "KS",
"New Mexico": "NM"
}
puts "-" * 10
# Printing states and their abbreviations
more_states.each do |state, abbrev|
puts "The abbreviation for #{state} is #{abbrev}"
end
more_cities = {
"OK": "Oklahoma City",
"TX": "Austin",
"CO": "Denver",
"KS": "Topeka",
"NM": "Santa Fe"
}
puts "-" * 10
# Printing state abbreviations and the corresponding state capitals
more_cities.each do |abbrev, capital|
puts "#{capital} is the capital of #{abbrev}"
end
puts "-" * 10
# Printing states, their abbreviations, and their capitals
more_states.each do |state, abbrev|
capital_city = more_cities[abbrev]
puts "The abbreviation for #{state} is #{abbrev}, and its capital is #{capital_city}"
end
我的前两个puts 工作正常,但是当我在more_states.each 中使用puts 时,我无法访问more_cities。
我也尝试过使用more_cities.fetch:
capital_city = more_cities.fetch(abbrev)
有了这个,我得到一个错误,它在more_cities 中找不到键“OK”,但那个键肯定在那里。
有什么建议吗?我觉得这是语法错误,或者我遗漏了什么。
【问题讨论】:
-
欢迎来到 SO!您的键是符号,但您使用的是字符串。尝试使用
=>而不是:或使用more_cities[abbrev.to_sym]制作哈希。
标签: ruby