In Cocoa, you can poke inside object graphs (and more!) using dotted strings:

Hey, did you notice that Objective-C sprouted some really handy literals for arrays and dictionaries lately? One could reasonably extrapolate that Apple has an interest in not breaking people’s fingers when they build for iOS and OS X.

There are libraries, e.g. Hashie, that make uniform access into object graphs, like you might get from an API response, as close to idiomatic Ruby as you probably want. Key paths, as implemented in Cocoa’s Key-Value Coding APIs, takes a different approach, using strings to define paths to traverse an object graph. I don’t really like “string programming”, but it’s an interesting approach, so let’s see where it takes us. Let’s add something like “key paths” to Ruby!

Enumerable is an awesome thing about Ruby. Let’s build key path traversal on top of that. The goal is something close to the Objective-C snippet above:

Turns out this isn’t hard to implement, even with a little error handling thrown in:

OK, first off, did you realize that SimpleDelegator makes it ridiculously easy to wrap objects with extra behavior? It sure does! Second, you could easily write this with a while loop or even a simple each, but why have local variables hanging around when you could use inject instead?![1] Third, this has more conditionals than I’d like, but it fits within 80 columns[2] so I’ll take it.

I’ve got this code, based on a whim. I’m not even sure it’s a good idea. Maybe it is!

Maybe it sucks?

I can’t really tell you, definitively, if you should try this or not. I’ve barely even used KVC in Cocoa! It’s a nifty idea, though, and it’s pretty rad that you can implement something like it in Ruby so trivially.

Now you know!