patternrubyMinor
Expressing multiple AND conditions in ruby
Viewed 0 times
conditionsexpressingmultiplerubyand
Problem
In ruby, is there a more concise way of expressing multiple AND conditions in an if statement?
For example this is the code I have:
Is there a better way to express this in Ruby? 1.9.2 or 1.9.3
For example this is the code I have:
if first_name.blank? and last_name.blank? and email.blank? and phone.blank?
#do something
endIs there a better way to express this in Ruby? 1.9.2 or 1.9.3
Solution
if [first_name, last_name, email, phone].all?(&:blank?)
#do something
endCaveat: While
and/&& short-circuit the expression (that's it, only the needed operands are evaluated), an array evaluates all its items in advance. In your case it does not seem something to worry about (they seem cheap attributes to get), but if you ever need lazy evaluation and still want to use this approach, it's possible using procs, just slightly more verbose:p = proc
if [p{first_name}, p{last_name}, p{email}, p{phone}].all? { |p| p.call.blank? }
#do something
endCode Snippets
if [first_name, last_name, email, phone].all?(&:blank?)
#do something
endp = proc
if [p{first_name}, p{last_name}, p{email}, p{phone}].all? { |p| p.call.blank? }
#do something
endContext
StackExchange Code Review Q#18223, answer score: 5
Revisions (0)
No revisions yet.