EDIT: I've received answers about refactoring to a ternary operation. While I'm aware that that's possible with all the languages below, that wasn't necessarily my intent with the original question about style. I've edited the snippets to reflect this.
I am curious if it's idiomatic or preferred to always use an else
when using if
/else
in a method.
For example, in JS, this is stylistically acceptable (and sometimes preferred)
function jsFunc(x) {
if (x == 0) {
// do a bunch of stuff here
return answer;
}
// do something else
return differentAnswer;
}
and I've also seen a similar style in Python:
def py_func(x):
if x == 0:
# do a bunch of stuff here
return answer
# do something here
return differentAnswer
but from the Ruby I've seen, it's always:
def ruby_method(x)
if x == 0
# do a bunch of stuff here
answer
else
# do something else
differentAnswer
end
end
I've also gotten a comment that not using an else
in Ruby seems messier. Do Rubyists prefer the explicit else
? (Also curious a lot of the language is implicit.)