[Ruby] [For beginners] How to get the Ruby delay train route name

1 minute read

I am currently studying ruby. I’ll write it here as a record.

Program outline

  1. Get delayed railway information from json of railway delay information
  2. Ask to enter the route name you want to check if it is delayed
  3. Based on the text information, search for the corresponding route in the obtained json information.
  4. If there is a corresponding route, output delay information. If not available, output as N/A

getting_delayed_trains_info.rb


require'open-uri'
require'nokogiri' # gem for scraping
call to use require'json' #json

parse #url
url ='http://tetsudo.rti-giken.jp/free/delay.json'
html = open(url).read
doc = Nokogiri::HTML(html, url)

Parse to #Json format and convert to hash
hash = JSON.parse doc.css("body").inner_text

# Enter the route name you want to check as standard and store it in input_train
puts "Please enter the route for which you want to know the delay status. Example: Keihin Tohoku Line"
input_train = gets.chomp

# delayed_trains array variable prepared
delayed_trains = Array.new
Store the delayed route name including the character string of # input_train and the updated date and time in delayed_trains
hash.each {|train| delayed_train << train["name"] + \
            '(Update date:'+ Time.at(train["lastupdate_gmt"], in: "+09:00").strftime("%Y-%m-%d %H:%M:%S"). to_s +')' \
            if train["name"].include? input_train}

# If the array is empty, there is no route for delay, otherwise the route name is output.
if delayed_trains.empty?
  puts "There is no delay on the route that contains the character "#{input_train}" that you sent."
else
  puts delayed_trains.join(",") + "It seems that there is a delay in \n Please see the railway company website for details."
end

There are some articles that have created parrots with LINE BOT, but I think that if you refer to it and put this algorithm, you can make a LINE BOT that will answer when you hear the route you are delaying or want to hear. ..

After all, I am motivated to learn that what I make is what I am studying.

Tags:

Updated: