I’m primarily a Rails developer, and so in whipping up a little script for my company’s Hubot instance, I was hoping to accomplish the following:
robot.brain.data.contacts ||= {}
Or, only make this new hash if it doesn’t already exist. The idea being that I want to have a contacts array added dynamically through the script so I don’t have to modify Hubot’s source, and I obviously don’t want to overwrite any contacts I add to it.
Question: is there a quick little construct like the Rails ||= that I can use in Coffeescript to achieve the above goal?
Cheers.
You can use
?=for conditional assignment:The
?is the “Existential Operator” in CoffeeScript, so it will test for existence (not truthiness):The resulting JS is a bit different in your case, though, because you are testing an object property, not just a variable, so
robot.brain.data.contacts ?= {}results in the following:More info: http://jashkenas.github.com/coffee-script/