HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Expressing multiple AND conditions in ruby

Submitted by: @import:stackexchange-codereview··
0
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:

if first_name.blank? and last_name.blank? and email.blank? and phone.blank?
      #do something
    end


Is 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
end


Caveat: 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
end

Code Snippets

if [first_name, last_name, email, phone].all?(&:blank?)
  #do something
end
p = proc
if [p{first_name}, p{last_name}, p{email}, p{phone}].all? { |p| p.call.blank? }
  #do something
end

Context

StackExchange Code Review Q#18223, answer score: 5

Revisions (0)

No revisions yet.