我们发现给定的代码检索到region_values 的以下值:
region_values
#=> [
{:region=>"Region01", :id=>1, :region_description=>"1 - Rockford Region Hospitals",
:ICUAvail=>126, :ICUCapacity=>234, :VentsAvailable=>296, :VentsCapacity=>359},
{:region=>"Region02", :id=>2, :region_description=>"2 - Peoria Region Hospitals",
:ICUAvail=>140, :ICUCapacity=>304, :VentsAvailable=>398, :VentsCapacity=>496},
{:region=>"Region03", :id=>3, :region_description=>"3 - Springfield Region Hospitals",
:ICUAvail=>77, :ICUCapacity=>150, :VentsAvailable=>350, :VentsCapacity=>410},
{:region=>"Region04", :id=>4, :region_description=>"4 - Edwardsville Region Hospitals",
:ICUAvail=>61, :ICUCapacity=>113, :VentsAvailable=>134, :VentsCapacity=>158},
{:region=>"Region05", :id=>5, :region_description=>"5 - Marion Region Hospitals",
:ICUAvail=>64, :ICUCapacity=>107, :VentsAvailable=>294, :VentsCapacity=>309},
{:region=>"Region06", :id=>6, :region_description=>"6 - Champaign Region Hospitals",
:ICUAvail=>70, :ICUCapacity=>162, :VentsAvailable=>260, :VentsCapacity=>287},
{:region=>"Region07", :id=>7, :region_description=>"7 - Southwest Suburbs Region Hospitals",
:ICUAvail=>175, :ICUCapacity=>484, :VentsAvailable=>444, :VentsCapacity=>589},
{:region=>"Region08", :id=>8, :region_description=>"8 - West Suburbs Region Hospitals",
:ICUAvail=>176, :ICUCapacity=>480, :VentsAvailable=>319, :VentsCapacity=>550},
{:region=>"Region09", :id=>9, :region_description=>"9 - Northwest Suburbs Region Hospitals",
:ICUAvail=>238, :ICUCapacity=>452, :VentsAvailable=>438, :VentsCapacity=>533},
{:region=>"Region10", :id=>10, :region_description=>"10 - Northeast Suburbs Region Hospitals",
:ICUAvail=>112, :ICUCapacity=>206, :VentsAvailable=>190, :VentsCapacity=>234},
{:region=>"Region11", :id=>11, :region_description=>"11 - City of Chicago Region Hospitals",
:ICUAvail=>395, :ICUCapacity=>1064, :VentsAvailable=>1392, :VentsCapacity=>1803}
]
在发布此之前,我不知道 Ruby v2.7 中的新模式匹配功能。阅读this article 后,我真的不明白这如何适用于您的问题(尽管该功能本身很有趣并且似乎很有用)。你可以写:
region_values.each do |h|
puts case h
in {id: 10}
'We found region 10!'
else
'aw shucks'
end
end
aw shucks
aw shucks
aw shucks
aw shucks
aw shucks
aw shucks
aw shucks
aw shucks
aw shucks
We found region 10!
aw shucks
或
found = region_values.find do |h|
case h
in {id: 10}
true
end
end
puts found ? 'We found region 10!' : 'aw shucks'
We found region 10!
但新功能的应用都不是很有趣。