unless
unless is the opposite of if: it runs the code only when the condition is false. It is like saying 'unless it is raining, we go outside'.
In this page:
Syntax
unless condition
# runs when condition is false
else
# otherwise
end
unless
unless condition runs its block only when the condition is falsy, acting as the inverse of if. It's used when the negated phrasing reads more naturally than if !condition.
unless also has a trailing modifier form, like puts "error" unless valid.
Note:
unless should generally only be used with simple conditions -- avoid pairing it with else, which is often confusing to read.Example: unless
logged_in = false
unless logged_in
puts "Please log in"
end
puts "Access denied" unless logged_in
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Adding an
elseor complex conditions withandtounless, which becomes hard to read; useifinstead. - Using
unlesswith a negation likeunless !logged_in, creating a confusing double negative. - Using
elsifwithunless, which is not allowed.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: