Last Updated: February 25, 2016
·
581
· mejarc

The Easy-Bake Oven, or Ruby's Array#map and Array#each

When I was a kid, there was a toy advertised on television called the Easy-Bake Oven.

Picture

The premise of it was that you could insert a pan containing a slurry of cake mix and water into one end of the oven, and a lightbulb inside the oven would bake the slurry into an edible, not reliably tasty, small cake that would pop out the other side.

I never got one--my mom was one of those killjoy health food enthusiasts who banned sugary snacks. Ah, well.

Anyway, the importance of the Easy-Bake Oven to me nowadays is as a metaphor when trying to remember the difference between Ruby's .each and .map methods on the Array object.

Consider the Ruby block as the Easy-Bake Oven. Between { and }, or do/end, there's your script's lightbulb transforming your input. So what's being popped out the other side?

That depends on the method:

  • if your oven is operating with .each, it doesn't bake the slurry. You get that nasty-tasting uncooked dough right back. But sometimes you're just showing off your new toy, and you've run out of cake mix, and you won't have enough cakes to share with everyone, so using .each is polite.

  • if your oven is operating with .map, it returns the desired baked good. Try it with .map! to really get rid of that uncooked dough once and for all.