Question

Is it idiomatic in Ruby to not explicitly return nil? Let's say something like this:

def find_something data
    if data.has_what_we_need?
        a = data.something
        if a.has_what_we_want?
            a.the_stuff[42]
        end
    end
end

As opposed to something (arguably noisier) like this:

def find_something data
    if data.has_what_we_need?
        a = data.something
        if a.has_what_we_want?
            a.the_stuff[42]
        else
            nil
        end
    else
        nil
    end
end
Was it helpful?

Solution

I try to create methods that bail out early if conditions aren't met, flattening the code in terms of indentation:

def find_something data
  return unless data.has_what_we_need?

  a = data.something

  return unless a.has_what_we_want?

  a.the_stuff[42]
end

This has two well defined exit points, as return should show up as a fairly obvious thing when reading it. A return with no argument will return nil to the caller.

If you don't care about nil vs. false you can condense this even more:

def find_something data
  return unless data.has_what_we_need?

  a = data.something

  a.has_what_we_want? and a.the_stuff[42]
end

OTHER TIPS

I'm unaware of a specific idiom pertaining to this, but this might be preferable:

def find_something data
    if data.has_what_we_need?
        a = data.something
        if a.has_what_we_want?
            return a.the_stuff[42]
        end
    end

    nil
end

If by idiomatic you mean does ruby by default return nil from a method then no.

Ruby methods by default return the value of the last statement executed. If your last statement resolves to nil then your method will return a nil.

I'm assuming from your example that you want a method to return a value if found but nil if not found. Something like this might work:

def find_something (i)
    a = ['boris', 'natasha', 'moose' ,'squirrel']
    a[i]
end


irb(main):020:0> find_something 4
=> nil
irb(main):021:0> find_something 2
=> "moose"`

The result from the index into array a is the return value.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top