Using Ruby's ternary operator ? : to shorten this

Scott

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)
mu is too short

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Using Ruby's ternary operator ? : to shorten this

From Dev

Ruby ternary operator (or) or operator

From Dev

Using ternary operator in python?

From Dev

Using of ternary operator in view

From Dev

Using the ternary operator in a macro

From Dev

Ruby ternary operator not returning as expected

From Dev

Understanding PHP's ternary operator

From Dev

Understanding PHP's ternary operator

From Dev

What's result of this ternary operator?

From Dev

"Do nothing" using ternary operator

From Dev

Using pattern matching with ternary if operator

From Dev

Using a concatenation operator with a ternary conditional?

From Dev

Assignment to expression using ternary operator

From Dev

Am I using the ternary operator?

From Dev

Using ternary operator to calculate the length

From Dev

Ruby ternary operator in erb with html tags

From Dev

2-Level Ruby Ternary Operator Not Working

From Dev

Ruby - Is it possible to use a ternary operator in a proc?

From Dev

Using Java's ternary operator, what's the implication of assigning a variable to itself?

From Dev

Ternary operator in CMake's generator expressions

From Dev

What's wrong with this strpos and ternary operator?

From Dev

C function call selection using ternary operator

From Dev

Ternary operator, syntax error when using assignment

From Dev

TCL conditional commands using ternary operator

From Dev

Assign null to decimal using ternary operator

From Dev

Performance difference using std::min or ternary operator?

From Dev

Using ternary operator on Console.WriteLine

From Dev

Using block with ternary operator in Objective-C

From Dev

How to use AND in if statement using ternary operator

Related Related

HotTag

Archive