gpt4 book ai didi

arrays - 如何将集合或数组放入二维 Ruby 哈希中?

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:11 24 4
gpt4 key购买 nike

我想创建一个二维散列来保存 Ruby 中的集合。我希望以下代码能够包含四个不同的集合,并且能够在哈希的第一维中列出键。

require 'set'

cities = Hash.new()
cities['Europe'] = Hash.new(Set.new)
cities['Asia'] = Hash.new(Set.new)

cities['Europe']['Sweden'].add "Stockholm"
cities['Europe']['Sweden'].add "Gothenburg"
cities['Europe']['Denmark'].add "Copenhagen"
cities['Europe']['Denmark'].add "Odense"

cities['Asia']['Japan'].add "Tokyo"
cities['Asia']['Japan'].add "Kyoto"
cities['Asia']['China'].add "Beijing"
cities['Asia']['China'].add "Shanghai"

p cities['Europe']
p cities['Asia']

p cities['Europe']['Sweden']
p cities['Asia']['Japan']

我得到以下输出:

{}
{}
#<Set: {"Stockholm", "Gothenburg", "Copenhagen", "Odense"}>
#<Set: {"Tokyo", "Kyoto", "Beijing", "Shanghai"}>

似乎哈希和集合的底层实现相互干扰,我得到了这个不直观的结果。如果使用数组而不是集合(即将 Set.new 替换为 Array.new 并将 .add 替换为 .push) 我得到了相同的、不需要的结果。

( ruby 版本: ruby 2.3.1p112)

最佳答案

当执行 h = Hash.new(Set.new) 时,访问哈希中不存在的键时返回的默认值将是 Set< 的实例,表示共享同一组。你可以这样检查:

h = Hash.new(Set.new)
h["Sweden"] << "Stockholm"
# => #<Set: {"Stockholm"}>
h["Denmark"] << "Copenhagen"
# => #<Set: {"Stockholm", "Copenhagen"}>
h["Sweden"].object_id == h["Denmark"].object_id
# => true

当访问散列中不存在的键时,它还会返回默认值,这意味着在访问散列时不会填充散列。

h = Hash.new(Set.new)
h["Sweden"]
# => #<Set: {}>
h
# => {}

您可以指定一个 block 以及调用 Hash.new .当访问哈希中不存在的 key 时,将使用哈希和 key 调用该 block 。该 block 应返回默认值。这是您可以在散列中存储 Set 的不同实例的地方,如下所示:

h = Hash.new { |hash, key| hash[key] = Set.new }
h["Sweden"] << "Stockholm"
# => #<Set: {"Stockholm"}>
h["Denmark"] << "Copenhagen"
# => #<Set: {"Copenhagen"}>
h
# => {"Sweden"=>#<Set: {"Stockholm"}>, "Denmark"=>#<Set: {"Copenhagen"}>}

您可以将它们结合起来以避免为每个大陆设置哈希值:

cities = Hash.new do |continents, continent_name|
continent_countries = Hash.new { |countries, country_name| countries[country_name] = Set.new }
continents[continent_name] = continent_countries
end
cities["Europe"]["Sweden"] << "Stockholm"
cities["Europe"]["Denmark"] << "Copenhagen"
cities["Asia"]["Japan"] << "Tokyo"
cities["Asia"]["Japan"] << "Kyoto"
cities
# => {"Europe"=>{"Sweden"=>#<Set: {"Stockholm"}>, "Denmark"=>#<Set: {"Copenhagen"}>},
# "Asia"=>{"Japan"=>#<Set: {"Tokyo", "Kyoto"}>}}

关于arrays - 如何将集合或数组放入二维 Ruby 哈希中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40338981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com