Ruby Tidbit: Super and Parameter Reassignment

Comments

Something I’ve always loved about Ruby is that no matter how long I’ve been using it, it continues to surprise and delight me with neat little tricks. Here’s one I was really surprised I never knew until now:

Let’s say you want to enforce some kind of parameter formatting on an inherited method. You probably already know that you can write something like:

def my_nifty_method(value)
  super(nifty_parameter_formatter(value))
end

But, did you know that you can also do this?

def my_nifty_method(value)
  value = nifty_parameter_formatter(value)
  super
end

I didn’t, until I just gave it a try this evening, for giggles. I figured it might work for methods that mutate an object, like Array#unshift, but since variable assignment is creating a new reference, I just assumed I’d need to explicitly pass in my modified value. Chalk me up as pleasantly surprised! Since I don’t ever remember seeing this information before, and a few quick Google searches turned up empty, I thought I’d share.

[Update: I’ve been informed this specific behavior was one of the topics covered in James Edward Gray II’s (aptly named) talk, “10 Things You Didn’t Know Ruby Could Do”. Worth a look for some other nifty tricks!]

comments powered by Disqus