Using conditional statements
Now that we know what types of variables we can use in Ruby, let’s give these variables some more practical use.
The if statement
By now, we should all be familiar with the if
statement and its structure: if a sentence is true, the code should do or return something.
Let’s take the person hash that we used in the previous section as our base:
person = { "name" => "Oscar", "age" => 35, "is_married" => true, "books_read_this_week" => 2.5 }
Using that, we can create a basic if
statement:
if person["is_married"] == true puts "Person is married" end
This is pretty much self-explanatory. This would read: “If the value in person["married"]
is equal to true, then print Person is married
.” The end
keyword limits when the if
statement is done – that is, anything after the end
keyword is not part of the block...