[Ruby] What is true?

I've been reading a technical book recently, and I think I understand it, I decided to output even the smallest details frequently.

This is an article for myself in the future.

Conclusion

In Ruby all values ​​except false and nil are true.

True and False

In Ruby, all data / values ​​are objects that belong to some class. Of course, true and false are no exception.

irb> true.class
=> TrueClass
irb> false.class
=> FalseClass

irb> true.class.ancestors
=> [TrueClass, Object, Kernel, BasicObject]
irb> false.class.ancestors
=> [FalseClass, Object, Kernel, BasicObject]

If all but false and nil are true, then 0 and (empty string) are also true.

#"0" is true
irb> p 0 ? true : false
true
=> true

#"" Is also true
irb> p '' ? true : false
(irb):15: warning: string literal in condition
true
=> true

However, in other languages ​​"0" is often false, and in JavaScript 0 and empty strings are falsy.

nil and false

There is a nil? Method to distinguish between nil and false.

irb> a = nil
=> nil
irb> a.nil?
=> true
irb> b = false
=> false
irb> b.nil?
=> false

When writing a Ruby program, nil may be mixed unexpectedly, so I often check nil, You can avoid nil objects by performing type conversion.

irb> nil.to_s
=> ""
irb> nil.to_i
=> 0
irb> nil.to_a
=> []
irb> nil.to_h
=> {}
irb> nil.to_sym
NoMethodError (undefined method `to_sym' for nil:NilClass)

to_sym is useless.

Postscript

I was confusing true/false with true/false in Ruby, but the following article was very helpful. Ruby true/false is different from true/false

Recommended Posts

[Ruby] What is true?
Is Ruby all objects, true?
[Ruby] What is `!!` used for?
[Ruby] What is an instance?
[Ruby on Rails] What is Bcrypt?
What is a Ruby 2D array?
What is Cubby
What is null? ]
What is java
What is Keycloak
What is maven?
What is Jackson?
What is self
What is Jenkins
What is ArgumentMatcher?
What is IM-Juggling?
What is params
What is SLF4J?
What is Facade? ??
What is Java <>?
What is POJO
What is Java
What is centOS
What is RubyGem?
What is before_action?
What is Docker
What is Byte?
What is Tomcat
[Technical memo] What is "include" in Ruby?
What is Maven Assembly?
What is `docker-compose up`?
What is a constructor?
What is vue cli
What is an interface?
What is Ruby's self?
What is hard coding?
What is a stream
What is Ruby's attr_accessor?
What is Java Encapsulation?
What is permission denied?
What is an initializer?
What is Spring Tools 4
What is an operator?
What is object orientation?
What is Guava's @VisibleForTesting?
What is MVC model?
What is an annotation?
What is Java technology?
What is Java API-java
What is @ (instance variable)?
What is Gradle's Artifact?
What is JPA Auditing?
[Swift] What is dismiss?
[Java] What is flatMap?
What is a Servlet?
What is web development?
[Java] What is JavaBeans?
[Android] What is Context? ??
[Java] What is ArrayList?
What is a safety reference operator (&.) Using Ruby ampersand?
What is object-oriented after all?