So far, we've behaved. All our arrays have been clean, containing only objects of the same type. (
Integer, etc.) However, we can abuse the fact that arrays permit disjoint types. "Disjoint types" are types which are grouped together (in our case, in an array) but which are not all of the same class. Before we even get started, a word of caution: though possible, one rarely has reason to put different types of objects in an array. Let's leave the discussion of when and when not to use this technique for after.
First off, let's have a quick look at just how disjoint an array can be:
Now, let's use Ruby's flexible, dynamic nature to solve a fake real-world problem. You are building a robot to take orders at The Tasty Gem Sandwich Shop. Any order placed at the shop can only account for one sandwich and one drink. (Don't ask me. It's been this way since 1954 when it opened.) Fortunately, the sandwich chef robot takes these orders in a sensible format: a hash. Less fortunate is the output he returns to each order robot: for some reason, he flattens the order hash into an array when he announces that an order is ready. This will cause us some trouble when we try look up which table we need to serve.
Fill out the template for your robot below. A customer will call the
place_order method, which you'll have to pass on to the chef robot with your robot's name. The chef will then call your robot's
serve method when the customer's sandwich is ready. Your robot needs to serve the correct sandwich/drink combo to the correct table at that point from the chef's sloppy data format.
As you can see, disjoint arrays are really not that clean. However, they are a reality someone else will present to you at some point. In this case, it was our beloved chef. But one day it may be the API of the social network de jour or a friend you're building something with. Knowing how to transform ugly data (a disjoint array) into pretty data (a hash) will alleviate much of the pain the former brings.