Вы были довольно близко. Вы хотите выяснить, что является контейнером для каждого отдельного местоположения, и зацикливаться на этом. В данном случае это .subbuzz
. Каждый .subbuzz
имеет .js-subbuzz__title-text
(название местоположения) и .subbuzz__description
(текст описания). Кроме того, я использовал один массив объектов для представления каждого местоположения, вместо того, чтобы пытаться поддерживать несколько массивов и синхронизировать значения.
В вашем коде также была важная опечатка. Вы инициализировали @travel_details = []
, но заполнили его, используя @@travel_details << ele....
. @travel_details
является переменной экземпляра. @@travel_details
является переменной класса. Они совсем другие. Я полагаю, вы получили Undefined method << for nil:NilClass
, когда из-за этого запустили свой код.
Если у вас есть какие-либо вопросы по этому поводу, обязательно задавайте!
Код:
# frozen_string_literal: true
require 'nokogiri'
require 'open-uri'
module TravelCli
Place = Struct.new(:title, :description, :image_url) do
def to_s
<<~TEXT
Title: #{title}
Description: #{description}
TEXT
end
end
class Places
URL = 'https://www.buzzfeed.com/louisekhong/bring-me-2019-best-travel-destinations'
def self.print
places = new
places.scrape
puts places.list.map(&:to_s).join("\n")
end
attr_reader :list
def scrape
@list = Nokogiri::HTML(open(URL)).css('.subbuzz').map do |place|
Place.new(
place.css('.js-subbuzz__title-text').text.strip,
place.css('.subbuzz__description').text.strip,
)
end
end
end
end
TravelCli::Places.print
Выход:
Title: Nairobi, Kenya
Description: Who'll love it: animal loversWhy go in 2019: Thanks to the recent launch of a direct flight route between Nairobi and New York City, spotting elusive lions and leopards on safari is now just that liiiiitttle bit easier. As both Africa's safari capital and one of the continent's fastest growing cities, Nairobi offers a unique contrast between the city and the wild.
Title: Juneau, United States
Description: Who’ll love it: foodiesWhy go in 2019: Juneau, Alaska, is having a foodie moment (I mean, why else would it be hosting the 2019 International Food Blogger Conference?). Focusing on fresh, local seafood and wild fruits, the food scene here is understated, delicious, and eco-friendly by nature. Be sure to check out Salt, an up-and-coming modern Alaskan restaurant that serves food foraged by the chef himself.
Title: Hong Kong
Description: Who’ll love it: solo travelers Why go in 2019: Hong Kong may be a small island, but it's bursting with culture! New and exciting attractions, including museums and a huge cultural center, make it the perfect city to explore solo. M+ Museum is slated to open this year and at 17,000 square meters, it'll be one of the largest museums of modern visual culture in the world. It's also one of the world's safest cities, which is comforting to know if you’re traveling on your own.
Title: Litchfield National Park, Australia
Description: Who'll love it: escapistsWhy go in 2019: With hiking trails through striking landscapes, epic 4WD tracks, and stunning waterfalls that lead to glistening natural pools, a visit to Litchfield National Park will make you forget that the rest of the world exists. Located ~90 minutes south of Darwin, it's smaller than the popular Kakadu National Park (and has fewer tourists!), and it's currently undergoing improvements that'll see new campgrounds and swimming spots open this year.
Title: Patagonia, Chile
Description: Who’ll love it: adventure seekersWhy go in 2019: Any serious adventurer will love the new massive hiking trail that connects 17 different national parks. Created as part of a huge conservation effort, the Route of Parks in Patagonian spans 1,740 miles and takes travelers on a scenic journey through parks like Torres del Paine and San Rafael Lagoon. It's the perfect way to experience some of Chile's incredible natural beauty.
Title: Yukon, Canada
Description: Who'll love it: nature loversWhy go in 2019: The Yukon territory is a prime place to catch a glimpse of the northern lights, and soon you'll be able to see them in a whole new way — on board a private jet! The Aurora 360 is taking flight for the first time in February, but if you don't make it in time for that, camping out in a tent is equally as magical. While you're there, make sure you visit Kluane National Park and Reserve to hike up Mount Logan, Canada's tallest peak.
Title: San Juan, Puerto Rico
Description: Who'll love it: conscientious travelers Why go in 2019: Since the devastation of Hurricane Maria in 2017, Puerto Rico has made huge strides in rebuilding the island and tourism is a key way to keep that regrowth underway. With amazing food (visit the famous Pork Highway just outside of San Juan), colorful architecture, and gorgeous natural beauty, traveling to the island this year doesn’t just benefit Puerto Ricans, but will also be a trip of a lifetime.
Title: Panama
Description: Who'll love it: party goers and beach bumsWhy go in 2019: This year marks the 500 year anniversary of Panama City and a celebration you won't want to miss. Special events such as parades, exhibitions, and musical shows are running until mid-August, but you can party with the locals and explore the historic old town year-round. When you're ready for some R&R, head up north to the blindingly white sand and clear waters of Bocas Del Toro.
Title: Matera, Italy
Description: Who’ll love it: history buffsWhy go in 2019: As one of the world’s oldest continuously inhabited cities, Matera has been named one of 2019’s European Capitals of Culture for its cultural importance (and stunning beauty). Its blend of ancient architecture and modern dining and entertainment is absolutely enchanting. Any place where you can spend days learning about 12th-century churches and nights dining on Italian food in an underground grotto restaurant is a winner for us.
Title: Yokohama, Japan
Description: Who'll love it: sports fansWhy go in 2019: Sporting fever is taking over Japan as it gears up for the 2019 Rugby World Cup in September (and let's not forget the Olympics in 2020). Just over 30 minutes south of Tokyo, the colorful harbor city of Yokohama is home to Japan's largest stadium and will play host to seven games — including the final. The food is also incredible: we recommend visiting the Shin-Yokohama Ramen Museum and snacking your way through Chinatown (it's the biggest in Japan!).