๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Ruby Comparisons

A comparison is a test that checks how two values relate. Every comparison has an answer of true or false.

Equal and not equal

The double equals sign tests equality. The != sign tests the opposite.

puts 5 == 5
puts 5 != 5
puts 5 == 6

Smaller and bigger

The angle signs compare size. Adding an equals sign lets the two values be equal.

puts 3 < 5
puts 3 > 5
puts 5 <= 5
puts 4 >= 5

Words in alphabet order

Words compare letter by letter in alphabet order. Apple comes before banana, so the first test is true.

puts "apple" < "banana"
puts "cat" == "cat"
puts "dog" > "cat"

Combining tests

The && sign needs both tests to be true. The || sign needs only one test to be true, and ! flips an answer.

age = 20
puts age > 18 && age < 30
puts age < 18 || age > 65
puts !(age == 20)

Example

score = 75
limit = 60
puts score == limit
puts score > limit
puts score >= 60 && score < 80
puts "apple" < "banana"

Key points

  • == tests whether two values are equal.
  • != tests whether two values are not equal.
  • < tests whether the first value is smaller than the second.
  • > tests whether the first value is bigger than the second.
  • <= tests whether the first value is smaller than the second or equal to it.
  • >= tests whether the first value is bigger than the second or equal to it.
  • Words compare by alphabet order.
  • &&, || and ! combine tests or flip an answer.

In this example, score is 75 and limit is 60. The first test asks whether the two values are equal, so it prints false. The second test asks whether score is bigger, so it prints true. The third test joins two tests with && and both are true. The last test compares two words by alphabet order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the code "apple" < "banana" print?