Concept Flow - Truthy and falsy values (only nil and false are falsy)
Start
Evaluate value
Is value nil or false?
Yes→Result: false (falsy)
No
Result: true (truthy)
End
Ruby treats only nil and false as false in conditions; everything else is true.
values = [nil, false, 0, "", [], {}] values.each do |v| puts v ? "truthy" : "falsy" end
| Iteration | Value | Condition (v ?) | Result | Output |
|---|---|---|---|---|
| 1 | nil | nil ? => false | false | falsy |
| 2 | false | false ? => false | false | falsy |
| 3 | 0 | 0 ? => true | true | truthy |
| 4 | "" | "" ? => true | true | truthy |
| 5 | [] | [] ? => true | true | truthy |
| 6 | {} | {} ? => true | true | truthy |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | After 6 | Final |
|---|---|---|---|---|---|---|---|---|
| v | nil | false | 0 | "" | [] | {} | {} | {} |
In Ruby, only nil and false are falsy. Everything else (0, empty string, empty array, etc.) is truthy. Use conditions like if value to check truthiness. This differs from some other languages. Remember: nil and false mean false; all else means true.
false and nil are falsy.0, empty string, and empty array are all truthy in Ruby.x is truthy in Ruby?if x automatically checks if x is truthy (not false or nil).if x == true only matches true, missing other truthy values; if x != nil treats false as truthy (false != nil); if x == nil checks the opposite of truthy.if x for truthy check [OK]value = 0 if value puts "Truthy" else puts "Falsy" end
value is assigned 0. The if value checks if value is truthy.0 is truthy, so the if branch runs.var is falsy. What is wrong?
var = nil if var == false puts "Falsy" else puts "Truthy" end
false and nil are falsy in Ruby.var == false, so it misses nil which is also falsy.arr = [false, nil, 0, "", [], true]Which code correctly returns only truthy values?
select { |v| v } keeps only truthy values because v in condition is true for truthy values.arr.select { |v| v != false } keeps nil (nil != false); arr.reject { |v| v } rejects truthy values; arr.select { |v| v == true } keeps only true, missing other truthy values.Pass the test and this pattern moves unknown