'What does this Ruby code do? unvisited_cities.min do |city|

I am working through a book on algorithms and it contains a description of Dijkstra's algorithm with a code sample in Ruby. The code solves a hypothetical problem of finding the cheapest flight path from city A to city B. You cannot necessarily fly directly from A to B, and so there may be multiple flights required to complete your trip.

A City object has a @name that is a String and @routes that is a hash with a City object as the key and ticket price as the value.

For example, the city of Atlanta is defined by

atlanta = City.new("Atlanta")
atlanta.add_route(boston, 100)
atlanta.add_route(denver, 160)
# where the add_route method states that 
@routes[city] = price

Further, unvisited_cities is an array of City objects, and cheapest_prices_table is a hash with a city @name as the key and ticket price as the value.

My question is, what does the following code, which is part of the Dijkstra algorithm code sample, do? I am unfamiliar with the syntax unvisited_cities.min do |city|. I placed a puts statement just above the code in question (p unvisited_cities.min), and I received an error: ArgumentError (comparison of City with City failed). I could not find a description of this syntax anywhere to understand exactly what the lines below do. That is, how does the code below set current_city to be the least expensive city to fly to in unvisited_cities?

# We visit our next unvisited city. We choose the one that is cheapest
# to get to from the STARTING city:
current_city = unvisited_cities.min do |city|
  cheapest_prices_table[city.name]
end

Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source