When it comes to working with APIs, two of the most common tools that you will use are JSON and XML. In this guide we’ll walk through a challenging task in which we ingest the full play of Shakespeare’s Macbeth in XML and convert it into a hash that sums the total number of lines for each character in the play.

Credit to Upcase for the great coding exercise.


Build out a method that sums the total number of lines of each character in Macbeth.

Exercise File

Code File

Exercise Description

Implement a method that parses Shakespeare’s Macbeth play (stored in XML). The method should return a hash, with the key being the name of the character and the value being the total number of lines the character had.

If you fork the coding exercise repo you can access the XML data in the support directory.

For reference, here is the XML source data.


macbeth_counter['ROSS'] # => 135
macbeth_counter['FLEANCE'] # => 2


# Full hash return value
  "First Witch"=>62,
  "Second Witch"=>27,
  "Third Witch"=>27,
  "LADY MACBETH"=>265,
  ["MACBETH", "LENNOX"]=>1,
  "Old Man"=>11,
  "First Murderer"=>30,
  "Second Murderer"=>15,
  "Both Murderers"=>2,
  "Third Murderer"=>8,
  "First Apparition"=>2,
  "Second Apparition"=>4,
  "Third Apparition"=>5,

Real World Usage

If you struggle with this exercise, don’t be discouraged. This is not a trivial coding exercise. There are a number of ways to implement this solution, and in fact in the next guide I’m going to show an alternative solution that refactors the solution and utilizes a functional approach. To properly build this program you will need to be able to:

  • Parse XML data
  • Convert XML data into a hash data structure
  • Worked with multiple nested iterators
  • Perform calculations on dynamic data


Can be found on the solutions branch on github.


Please enter your comment!
Please enter your name here