I just kinda ran against a wall here. Let's say my code is something like the following:
def foo
if bar
123
else
nil
end
end
Here the return value is either Int or Nil. I'm used to the concept of optionals (in languages like Rust, F#, Haskell) and this is really confusing me.
I realize that I can return a value of any type without problems, but coming from a more functional background it just feels wrong.
In Rust, I'd return an Option<T>
. That way I could easily test whether Some
value was returned, or no value (None
). In Ruby/Crystal that seems like a silly thing to do though.
So, here's the question:
Should I just return nil
in the case that there is no useful value to return and test against that, and is this the idiomatic way of handling such cases? If not, how should I do it in an idiomatic way?
Yes, return
nil
Returning
nil
is the encouraged best practice in Ruby. You can check for that withfoo.nil?
NB, if you are interested in learning more best practices for Ruby, best refer to the book "Ruby Best Practices" by Gregory Brown.
On a related note, the language defaults to returning
nil
in many places. For example, when anif
expression has no else block it's return value for the else block isnil
.So you can simplify your example as
which will return
nil
ifbar
is not truthy