【问题标题】:How to print Hash data in Ruby [duplicate]如何在Ruby中打印哈希数据[重复]
【发布时间】: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


【解决方案1】:

密钥类型(String v Symbol

more_cities 中的键是一个符号(例如,:OK);然而,在more_states 中,abbrev 是一个文字字符串(例如,'OK')。一种解决方案是通过String.to_sym 方法将字符串转换为符号。


代码更新

注意第二行 abbrevabbrev.to_sym

more_states.each do |state, abbrev|
  capital_city = more_cities[abbrev.to_sym]  # <-- here
  puts "The abbreviation for #{state} is #{abbrev}, and its capital is #{capital_city}"
end



补充

如需更多阅读,请参阅这些资源以描述字符串 v 符号:

【讨论】:

    猜你喜欢
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2012-10-23
    • 2022-12-10
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多