Ruby code Myjson.rb require \'json\' require \'pp\' require \'net/http\' url = \
ID: 3829149 • Letter: R
Question
Ruby code
Myjson.rb
require 'json'
require 'pp'
require 'net/http'
url = 'http://api.apixu.com/v1/current.json?key=72758ce44d72440a818195031171902&q=Denver,CO'
uri = URI(url)
response = Net::HTTP.get(uri)
j=JSON.parse(response)
pp j
puts "The temperature in #{j['location']['name']} is #{j['current']['temp_f']} degrees."
Add a function (and call it) to compare the weather in two cities. (Google knows all if you don't!) You can use if statements and logical and or statements. Print out which city currently has "better" weather than another, and print your reasoning. (If you are a skier, or hate rain, Orlando wouldn't be "better") Compare a couple of fields in addition to the temperature.
Explanation / Answer
Here is the solution, i have just compared the temperature, you can just add more conditions like if you want to compare temperature of first city k and 2 city j put if "{k['current']['temp_f']}" < "#{j['current']['temp_f']}"
require 'json'
require 'pp'
require 'net/http'
url = 'http://api.apixu.com/v1/current.json?key=72758ce44d72440a818195031171902&q=Denver,CO'
uri = URI(url)
response = Net::HTTP.get(uri)
k=JSON.parse(response)
puts "The temperature in #{k['location']['name']} is #{k['current']['temp_f']} degrees."
url = 'http://api.apixu.com/v1/current.json?key=72758ce44d72440a818195031171902&q=Boulder,CO'
uri = URI(url)
response = Net::HTTP.get(uri)
j=JSON.parse(response)
puts "The temperature in #{j['location']['name']} is #{j['current']['temp_f']} degrees."
if "#{k['current']['temp_f']}" < "#{j['current']['temp_f']}"
puts "#{k['location']['name']} is better."
else
puts "#{j['location']['name']} is better."
end
Output:
The temperature in Denver is 45.0 degrees.
The temperature in Boulder is 59.0 degrees.
Denver is better.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.