0
0
Rubyprogramming~5 mins

Inline if and unless (modifier form) in Ruby

Choose your learning style9 modes available
Introduction

Inline if and unless let you write simple conditions in one line. This makes your code shorter and easier to read for small checks.

When you want to run a single action only if a condition is true.
When you want to skip an action unless a condition is met.
When you want to keep your code compact and clear for simple decisions.
Syntax
Ruby
action if condition
action unless condition

The if modifier runs the action only when the condition is true.

The unless modifier runs the action only when the condition is false.

Examples
This prints "Hello" because the condition is true.
Ruby
puts "Hello" if true
This prints "Skip" because the condition is false, so unless runs the action.
Ruby
puts "Skip" unless false
This does not print anything because the condition is false.
Ruby
puts "No print" if false
This does not print anything because the condition is true, so unless skips the action.
Ruby
puts "No print" unless true
Sample Program

This program checks if the age is 18 or more. It prints "You can vote" if true, otherwise it prints "You cannot vote".

Ruby
age = 20
puts "You can vote" if age >= 18
puts "You cannot vote" unless age >= 18
OutputSuccess
Important Notes

Use inline if/unless only for simple, short actions to keep code readable.

For multiple actions or complex logic, use full if/unless blocks.

Summary

Inline if/unless help write short conditional actions in one line.

if runs action when condition is true; unless runs when false.

Keep it simple to keep your code clear and easy to understand.