Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Common Ruby conditionals refactored to boolean expressions

Redundant if/else - identity

def can_edit?
  if admin?
    true
  else
    false
  end
end

# Condition is redundant.
# Just return the boolean directly

def can_edit?
  admin?
end

Redundant if/else - negation

def reader?
  if admin?
    false
  else
    true
  end
end

# This is just flipping the boolean
# Use ! (NOT) instead

def reader?
  !admin?
end

! (boolean NOT) re-implemented with guard clauses

def reader?
  return false if admin?
  true
end

# This is just flipping the boolean
# Use ! (NOT) instead

def reader?
  !admin?
end

|| (boolean OR) re-implemented with guard clauses

def can_edit_admin_post?
  return owner? unless admin?
  true
end

# The flow of logic is hard to follow here
# Use || (OR) instead

def can_edit_admin_post?
  owner? || admin?
end

&& (boolean AND) re-implemented with guard clauses

def can_edit_admin_post?
  return owner? if admin?
  false
end

# The flow of logic is hard to follow here
# Use && (AND) instead

def can_edit_admin_post?
  owner? && admin?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment