Ah, the <blink> tag. The internet’s version of the cowbell. In an effort to start giving back more to the Ruby community (big fan!), I’ve decided to start a more technical blog and talk a bit about programming languages, software development with distributed teams and sundry other topics. As this blog’s title might imply, I will endeavour to entertain as well as elucidate.
As a way to kick off my new year’s resolution to blog more about technical matters, I thought I’d share this nugget of Ruby syntax fun. Say you’ve got the following code:
Simple enough, no? Well, then this is exactly what you’d expect:
Hold on. Why does calling foo with nil as an argument result in ‘nil’ being printed out?
The answer is actually spelled out in the Pickaxe book, though it’s rather subtly worded:
Ruby lets you specify default values for a method’s arguments—values that will be used if the caller doesn’t pass them explicitly.
In the first case, we’re explicitly passing the value nil, so our default parameter value isn’t used. In the second case, we’re passing no arguments to the method, so we get the default.