0
0
Rubyprogramming~5 mins

Truthy and falsy values (only nil and false are falsy) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Truthy and falsy values (only nil and false are falsy)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of values grows, the program checks each one once.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of values; double the values, double the checks.

Final Time Complexity

Time Complexity: O(n)

This means the time to check truthy or falsy values grows in a straight line with the number of values.

Common Mistake

[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.

Interview Connect

Understanding how simple checks like truthiness scale helps you reason about code efficiency and write clearer, faster programs.

Self-Check

"What if we changed the array to include nested arrays or hashes? How would the time complexity change?"