b = a
b = 0
If you were more versed in other more dynamically typed languages, you'd rather write it in ruby as:
It seems a bit obtuse, but I think this structure is invoked so often in my experience, that the shorthand is actually quite welcome. And it's not too bad once you know what it is.
b = a || 0
In Erlang (and I think Haskell), there are guards for a function. Guards are basically a condition that must exist before the function is run. If you were coming from a C or Java background, you'd probabily write it in ruby as:
But really, it can be written as:
b = a.some_method()
b = a && a.some_method
b = a.some_method unless a.nil?
I think the latter is more readable, but there would be no default if 'a' didn't exist. With the bitwise operators, you can chain it:
b = (a.respond_to?(:gsub) && a.gsub(/h/, '')) || "default!"
Now, that's starting to be hard to read. It has a guard for a, so that it doesn't raise an error when it tries to run gsub() if a is nil, and if it is nil, it will return the default. With this kind of thing, you'd want to be judicious and careful when using it. It's definitely easy to go crazy with this sort of thing. Remember, the goal is ease of readability, cuz you only ever write a line once, but you read it lots of times.