askvity

Is 0 true in Ruby?

Published in Ruby Programming 2 mins read

Yes, 0 is considered true in Ruby.

Truthiness in Ruby

In Ruby, only false and nil are considered false values. Every other value, including numerical values like 0, empty strings (""), and empty arrays ([]), evaluates to true in a boolean context. This concept is known as "truthiness."

Why 0 is True

Unlike some other programming languages where 0 is often treated as a representation of false, Ruby treats it as a valid value. The boolean interpretation of a value in Ruby depends on whether it is literally false or nil, not its numerical or logical equivalent in other contexts.

Examples

Here are some examples to illustrate this behavior:

if 0
  puts "0 is true" # This will be printed
end

if ""
  puts "Empty string is true" # This will be printed
end

if nil
  puts "nil is true" # This will NOT be printed, because nil is falsey.
end

if false
 puts "false is true" # This will NOT be printed, because false is falsey.
end

Summary

In summary, Ruby treats all values as true except for false and nil. Consequently, 0 is considered true in Ruby's boolean context.

Related Articles