Sandwich Scheduling: a look at Ruby's Array cycle method

How Ruby can help you schedule your sandwiches

How Ruby can help you schedule your sandwiches
Photo: Suzy Hazelwood

Now that the kids are going back to school, Derek is having to get back into the routine of making a packed lunch for his son each morning. Unfortunately, Derek’s son is a bit of a demanding customer. He likes three kinds of sandwich, cheese, tuna, and ham, and insists on having these on a strict rota system. This means that if he had cheese yesterday, he’ll want tuna today, ham tomorrow, and then back to cheese the day after that. To further complicate things, Derek’s son has two lunchboxes, a Minecraft branded one, and a Spider-Man branded one, and he likes to alternate between the two.

To keep track of all this, Derek would like some Ruby code that will list which sandwich filling and lunchbox should be used on a particular day. He starts by creating three Arrays, one for the days of the week, one for the sandwich fillings, and one for the lunchboxes:

days = %w[Monday Tuesday Wednesday Thursday Friday]
fillings = %w[cheese ham tuna]
boxes = %w[Minecraft Spider-Man]

Derek is going to use the Array cycle method to, well, cycle through each of these arrays and produce the schedule. Let’s look at his code:

days = %w[Monday Tuesday Wednesday Thursday Friday].cycle
fillings = %w[cheese ham tuna].cycle
boxes = %w[Minecraft Spider-Man].cycle

puts "Sandwich schedule for next two weeks:"

10.times { puts "#{days.next}: #{fillings.next} sandwich in my #{boxes.next} lunchbox." }

The first three lines set up three Enumerators, each of which will return the array’s elements one at a time. When the end of the array is reached, the Enumerator will go back to the start, and will happily keep on doing so forever. The final line is where the magic happens. We’re asking each Enumerator ten times for the next element in the sequence, and displaying them on the screen to produce the schedule. The above code will produce the following output:

Sandwich schedule for the next two weeks:
Monday: cheese sandwich in my Minecraft lunchbox.
Tuesday: ham sandwich in my Spider-Man lunchbox.
Wednesday: tuna sandwich in my Minecraft lunchbox.
Thursday: cheese sandwich in my Spider-Man lunchbox.
Friday: ham sandwich in my Minecraft lunchbox.
Monday: tuna sandwich in my Spider-Man lunchbox.
Tuesday: cheese sandwich in my Minecraft lunchbox.
Wednesday: ham sandwich in my Spider-Man lunchbox.
Thursday: tuna sandwich in my Minecraft lunchbox.
Friday: cheese sandwich in my Spider-Man lunchbox.

Which is perfect for printing out and sticking on the fridge door.

I’d love to hear your thoughts on cycle, the uses you’ve found for it, and indeed, sandwiches. Why not leave a comment below?


Related Posts

Let's Work Together

We would love to hear from you so let's get in touch!

CONTACT US TODAY!