Boolean values (true, false, nil) in Ruby - Time & Space Complexity
When working with Boolean values like true, false, and nil in Ruby, it is helpful to understand how fast these checks run.
We want to know how the time to check these values changes as the program runs.
Analyze the time complexity of the following code snippet.
values = [true, false, nil, true, false]
values.each do |val|
if val == true
puts "It's true!"
elsif val == false
puts "It's false!"
else
puts "It's nil or something else"
end
end
This code checks each value in a list to see if it is true, false, or nil and prints a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for each element in the array.
As the number of values grows, the program checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the list gets longer.
[X] Wrong: "Checking true, false, or nil is slow because it involves many conditions."
[OK] Correct: Each check is simple and fast; the main time cost comes from how many items you check, not the conditions themselves.
Understanding how simple checks scale helps you explain your code's speed clearly and confidently in real situations.
"What if we changed the array to a nested array and checked values inside each sub-array? How would the time complexity change?"