In Ruby, you’ll find that all of the standard logic operators that most languages have, are supported.
Symbol | Meaning |
---|---|
< | Less than |
> | Greater than |
== | Equals |
!= | Not equals |
>= | Greater OR equal to |
<= | Less OR equal to |
Conditionals
Of course, conditionals such as an if statement are also possible within Ruby. Similar to Go, there are no parenthesis around the conditional statement.
stock = 1
if stock < 1
puts "Sorry we are out of that item."
end # the end of our if statement
Notice that you also have an end
statement, instead of braces like in C/C++/Java/Go.
The Else Statement
Likewise, you also have an else statement to go with your if statement.
For example you might have:
if stock < 1
# the true block
puts "Sorry we are out of that item."
else
# the false block
puts "Thank you for your order."
end
Else If Statements
Similar to Python, there is a special command for else if. It is the elsif
keyword.
=begin
This will be used to show the entire possible If/Else If/Else block
Look to see how we are using it.
=end
stock = 35
if stock < 1
puts "Sorry we are out of that item."
elsif stock > 10
# else if statement... if there are too many items give a discount to sell them
puts "You get a special discount!"
else
puts "Thank you for your order."
end
Notice Multiline Comments
Notice in this last block of code, there are multiple lines of comments. They start with the =begin
and end with =end
.
This is intuitive, but a bit verbose compared to many other languages.
Boolean Logic
Boolean logic operators for and (&&
) and or (||
) are the same as they are for most languages we’ve looked at.
Strings and Conditions
Strings in Ruby are case sensitive. So you need to test in a manner appropriate for what you are doing.
# check for case insensitivity
username = "Walter"
expected_username = "walter"
if expected_username.downcase == username.downcase
puts "Username is correct."
end
# check for case sensitivity
password = "123abc!"
expected_password = "123AbC!"
if expected_password == password
puts "Password is correct."
end
Notice the use of downcase
to send it to lower case. If you want a string to be all caps, use upcase
.
Basic Logic in Ruby was originally found on Access 2 Learn
One Comment
Comments are closed.