Ruby Medium technical 1 views 1 min read

How does truthiness work in Ruby, and what is nil?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Ruby conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

In Ruby only nil and false are falsy. Everything else, including 0, "", empty arrays and empty hashes, is truthy. This differs from many languages and is a common source of bugs.

puts "truthy" if 0        # prints, 0 is truthy
puts "yes" if []          # prints, [] is truthy

value = nil
value ||= 10              # assign if nil or false
puts value.inspect        # 10

nil is the single instance of NilClass and responds to nil?; Object#nil? returns false for everything else. Test emptiness explicitly with empty? or, in Rails, present?. ||= assigns when the variable is nil or false.

Calling a method on nil raises NoMethodError, but safe navigation short-circuits: user&.profile&.name. nil.to_s is an empty string and nil.to_a is an empty array, which is why Array(nil) and String(nil) are useful conversions.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?