I'm experimenting with the new pattern matching feature in Ruby 2.7 by pattern matching against a JSON document. I would like to use it to match only on array elements with certain characteristics. In my case, there's an array of region data stored as hashes that each have an id. I only need to match against the hash with an id
of 10
as seen below:
require 'net/http'
require 'json'
HOSPITAL_DATA_URI = URI("https://www.dph.illinois.gov/sitefiles/COVIDHospitalRegions.json?nocache=1").freeze
hospital_data = JSON.parse(Net::HTTP.get(HOSPITAL_DATA_URI), symbolize_names: true)
region_values = hospital_data[:regionValues]
case region_values
in [{id: 10, **unimportant_attributes}, **non_region_10_hashes]
puts 'We found region 10!'
else
puts 'aw shucks'
end
puts "...but Region 10 does exist" if region_values.find {|region| region[:id] == 10}
#=> aw shucks
#=> ...but Region 10 does exist
I expect it to print "we found region 10!" but it does not.
Is it possible to use Ruby pattern matching to do this?
We find that the given code retrieves the following value for
region_values
:Before posting this I was unaware of the new pattern matching feature in Ruby v2.7. After reading this article I don't really see how this applies to your problem (though the feature itself is interesting and seems potentially useful). You could write:
or
but neither is a very interesting application of the new feature.