What is the idiomatic way of returning optional values?

758 Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

Yes, return nil

Returning nil is the encouraged best practice in Ruby. You can check for that with foo.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 an if expression has no else block it's return value for the else block is nil.

So you can simplify your example as

def foo
  123 if bar
end

which will return nil if bar is not truthy

0
On

In Crystal nil is the preferred way to indicate the absence of a value, and is usually combined with other values to mean "something can either be returned (T) or not (Nil)". The API docs also explain this and mention several ways to deal with nil: https://crystal-lang.org/api/0.20.1/Nil.html