Using Ruby's ternary operator ? : to shorten this

256 Views Asked by At

I wonder if there’s a way to tighten this up:

def find_by_recordtype
  e = EvLk.find_by_sql(<SQL QUERY>)
  return (e.size > 0 ? e : nil)   
end

I could do something like below but, prefer not to query twice.

  return ( EvLk.find_by_sql().size > 0 ? EvLk.find_by_sql() : nil)
3

There are 3 best solutions below

1
On BEST ANSWER

You're using find_by_sql so presumably you're in Rails or have ActiveSupport available. In that case, you can use presence:

presence()

Returns the receiver if it's present otherwise returns nil. object.presence is equivalent to

object.present? ? object : nil

So you could do this:

def find_by_recordtype
  EvLk.find_by_sql(<SQL QUERY>).presence
end
2
On

One thing you can do is memoize the result.

Whether this makes sense depends on the context of the object and the app.

def find_by_recordtype
  return @records if @records

  @records = EvLk.find_by_sql(<SQL QUERY>)
end

+1 for ruby nuby.

BTW, why do you want to return nil? Usually it's better to the same type for all cases.

2
On
EvLk.find_by_sql(<SQL QUERY>).tap{|e| break if e.empty?}