Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created December 5, 2018 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelQ/cd1f25711bccf11df7d1236728d5a900 to your computer and use it in GitHub Desktop.
Save JoelQ/cd1f25711bccf11df7d1236728d5a900 to your computer and use it in GitHub Desktop.
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