Articles Feed

Authors

Categories

Meta-programming Comes Naturally to Intern

by: doug | June 22nd, 2009 |

We have a couple of interns in the office this summer. They are kind of like Jr. Apprentices - distinguished mostly by the fact that they are in school and will be returning to school in the fall. I've been working with Andrew this summer. He just finished his Sophomore year of High School and is just learning to program. He's been working through a couple of ruby tutorials: Chris Pine's Learn to Program in Ruby and the ever-so-entertaining-especially-for-a-high-schooler Why's Poignant Guide to Ruby.

He was working on the Orange Tree example for Pine's tutorial. He had the class written and want to write a command line interface to it. This was what he tried to do.

  1. tree = OrangeTree.new
  2. command = gets
  3. tree.command

"What are you trying to do Andrew?"

"I want to get a command from the user and call that command on the tree object."

Now I had expected that Andrew would write a big if-else chain comparing strings and calling methods. In my mind that's what a beginning programmer should learn. I learned to program in C++ and that's the way I had to do it! I wasn't even sure that we would even touch meta-programming this summer.

But I had a second thought. "Why not show him some Meta Programming now?" I don't want to be responsible for destroying the future career of an aspiring programmer, but what the heck? How much damage could it possibly do?

So I explained to Andrew how methods in Ruby aren't really methods, they are messages and how you can "send" a message to an object. We modified his program to do what he wanted.

  1. tree = OrangeTree.new
  2. command = gets.chomp.to_sym
  3. tree.send(command) if tree.responds_to?(command)

I'm not sure that he completely understood all that, but there it is. Ruby let Andrew do the thing that he naturally wanted to do.

4 Responses to “Meta-programming Comes Naturally to Intern”

  1. Frank Quednau Says:

    That is quite elegant.

  2. Dan Says:

    Great! Maybe we should pay more attention to how juniors try to program instinctively - could it prove fruitful for language design? I remember making similar kinds of "mistakes" to Andrew's first attempt when I was first starting out with programming... but of course I'd never make that kind of mistake now because I'm old and cynical and know better. Perhaps we lose something as we become experienced programmers?

  3. id10tsavant Says:

    Great, now lets hope the method doesn't have any arguments and isn't never overridden. Or can ruby handle that too? Seems like it might due to dynamic typing.

  4. JJ Says:

    Andrew has a perfect understanding of the semantics. He just didn't quite grok details.

    C++, Java, etc., would punish him for not molding his thought process to the language straight-jacket.

Leave a Reply

#