Skip to content

Instantly share code, notes, and snippets.

@Martin-Alexander
Last active May 6, 2020 16:06
Show Gist options
  • Save Martin-Alexander/b6d3731217ce4a217b0826b9f8ba3a71 to your computer and use it in GitHub Desktop.
Save Martin-Alexander/b6d3731217ce4a217b0826b9f8ba3a71 to your computer and use it in GitHub Desktop.

Comparison Between AJAX and Ruby

Both of these pieces of code:

  • Make an HTTP GET request to the same URL
  • Parse the response (which is in JSON format) into datatypes (Hash for Ruby and Object for JavaScript)
  • Retrieve the results array and iterate over each Star Wars character

Ruby

require "open-uri"
require "json"

response = open("https://swapi.co/api/people/").read
data = JSON.parse(response)
data["results"].each do |person|
  puts "#{person['name']}"
end

JavaScript

fetch("https://swapi.co/api/people/")
  .then(response => response.json())
  .then((data) => {
    data.results.forEach((person) => {
      console.log(person.name);
    });
  });

Step by Step

fetch("https://swapi.co/api/people/")

Get the raw data from the server in JSON format.

.then(response => response.json())

Take that raw data and turn it into an Object.

 .then((data) => {
   data.results.forEach((person) => {
     console.log(person.name);
   });
 });

Get the results array from the object and iterate over each element (Star Wars character) and print the name property to the console.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment