The double-splat operator is one of my favorite additions in Ruby 2.0. For some reason, the two little asterisks together make me happier than an optional
Hash parameter in a method. Even so, outside of method definitions, I didn’t realize there was a use for the double-splat operator until I dug into a bug in Hashie. I liked the result enough that I wanted to take a quick minute and share what I found.
Sometimes you don’t yet have enough information to create an object. When that happens Hash is a great proxy for an object until you understand your domain a little better. I wanted the same behavior in Ruby for building up Hashes in these cases. For a while, I relied on
Hash#merge, but then I saw this bug on Hashie.
To solve this problem, you can use the double-splat operator in a different way. Check out the following code:
Interestingly, if you compile down the instruction sequence for this code, you will see that it uses the C version of
Hash#merge under the covers. I like that I’m getting the semantics of
If there’s one way to do something in Ruby, there’s probably at least one more. I think this is one of the reasons many people like Ruby: they can express their thoughts in the manner that is easiest for them.
That’s all I have for you today. Did you know about the double-splat operator in this case?