Truthy and falsy values (only nil and false are falsy) in Ruby - Time & Space Complexity
We want to understand how checking if a value is truthy or falsy affects the time it takes to run a program.
Specifically, how does the program's work change when it tests values like nil or false?
Analyze the time complexity of the following code snippet.
values = [nil, false, 0, '', true, [], {}]
values.each do |val|
if val
puts "Truthy"
else
puts "Falsy"
end
end
This code checks each value in a list to see if it is truthy or falsy, then prints a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array and checking its truthiness.
- 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 work grows directly with the number of values; double the values, double the checks.
Time Complexity: O(n)
This means the time to check truthy or falsy values grows in a straight line with the number of values.
[X] Wrong: "Checking if a value is truthy or falsy takes longer for some values like 0 or empty strings."
[OK] Correct: In Ruby, only false and nil are falsy; all other values, including 0 and empty strings, are truthy and checked in the same quick way.
Understanding how simple checks like truthiness scale helps you reason about code efficiency and write clearer, faster programs.
"What if we changed the array to include nested arrays or hashes? How would the time complexity change?"