Conditionals Guide in Ruby
In this section, we are going to talk about conditionals in Ruby, which let our programs make decisions based on varying data.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this section, we are going to talk about conditionals in Ruby. This is a very important component of learning how to code since conditionals allow our programs make decisions based on varying data.

Real World Use of Conditionals

Imagine that you're building a self driving car. Your car would have sensors providing information such as GPS coordinates, the location and speed of the vehicles around the car, and the list goes on and on.

All of this data is great, however how can we use it to make sure our car functions properly? Our program could follow a set of rules, below are a few basic ones:

  • if the speed limit is 40 MPH, ensure to match the speed.
  • if there is an accident in front of the car, slow down.
  • if the car has less than 1/4 of fuel then stop at a gas station.

Do you notice how each of these requirements evaluate a parameter and change the behavior of the car based on its value? This is how conditionals work.

At a high level conditionals analyze a scenario, compare it with the data provided, and then alters the flow of a program based on the results.

Code Example of Conditionals

Let's start with the most basic conditional - the standard if statement:

x = 10
y = 5

if x == y
  puts "x is the same as y"
else
  puts "x and y are not the same"
end

If you run this code, the message is x and y are not the same.

If I change the value of x to 5, and run it, the message is x is the same as y.

Do you see how you can almost read the code like plain language? This easy to read syntax is one of the reasons so many developers have fallen in love with Ruby. This conditional can be read as:

If x is equal to y, print out "x is the same as y", else, print out "x and y are not the same"

In the next guides we'll walk through how we can implement conditionals into programs and give programs dynamic behavior.