DEV Community

salcasta
salcasta

Posted on

Ruby Basics - Control Flow

if statement

if is used to see if something is either true or false

if 1 < 2
  print "I'm getting printed because one is less than two!"
end
Enter fullscreen mode Exit fullscreen mode

if the 1 was changed to 3, nothing would be printed

else statement

Using else after if checks for one condition, if that condition is not met then the else condition will run automatically

if 1 > 2
  print "I won't get printed because one is less than two."
else
  print "That means I'll get printed!"
end
Enter fullscreen mode Exit fullscreen mode

elsif statement

Using elsif allows you to add more conditions before the else condition is used

if x < y  # Assumes x and y are defined
  puts "x is less than y!"
elsif x > y
  puts "x is greater than y!"
else
  puts "x equals y!"
end
Enter fullscreen mode Exit fullscreen mode

Unless

Using unless checks to see if a statement is false instead of true

hungry = true

unless hungry
  puts "I'm writing Ruby programs!"
else
  puts "Time to eat!"
end
Enter fullscreen mode Exit fullscreen mode

Equal signs

Using = sets a variable
Using == compares to variables to see if they are equal
Using != compares to variables to see if they are not equal

is_true = 2 != 3

is_false = 2 == 3
Enter fullscreen mode Exit fullscreen mode

Greater than and Less than

Compare number variables to see if one variable is greater than > or less than < another number variable

test_1 = 17 > 16

test_2 = 21 < 30

test_3 = 9 >= 9

test_4 = -11 <= 4
Enter fullscreen mode Exit fullscreen mode

Using logical operators

Ruby allows you to use logical or boolean operators such as AND && OR || NOT !

boolean_1 = (3 < 4 || false) && (false || true)
boolean_1 = true

boolean_2 = !true && (!true || 100 != 5**2)
boolean_2 = false

boolean_3 = true || !(true || false)
boolean_3 = true
Enter fullscreen mode Exit fullscreen mode

Project

The mini project for this section showed you how to take an letter from a user's input and switch it to something else!

print "Print your name:"
user_input = gets.chomp
user_input.downcase!

if user_input.include? "s"
   user_input.gsub!(/s/, "th")
else puts "Name can not be changed :/ " 
end

puts "Your name is #{user_input}!"

#Salvador => Your name is thalvador!
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
heratyian profile image
Ian

these are great. Try using markdown code blocks for better formatting in your blog post.

print "Print your name:"
user_input = gets.chomp
user_input.downcase!
Enter fullscreen mode Exit fullscreen mode

Image description

Collapse
 
salcasta profile image
salcasta

Thanks!! Updated my posts on ruby using markdown code blocks