How to convert an object to boolean in Ruby?

1

Objects in Ruby have some methods for rendering into another type, such as:

  • to_s : convert to string
  • to_a : convert to array
  • to_i : convert to integer
  • to_f : convert to float

But there is no standard method for converting an object to boolean, nor in the Object class. How to do this conversion?

    
asked by anonymous 27.12.2017 / 04:09

1 answer

1

The idiomatic way of converting an object of any type to boolean in Ruby is by using a double negation (also called a double bang in the Ruby community):

def to_b(obj)
  !!obj
end

The double negation does not affect the value, such that:

!!true  => true
!!false => false

Remember that in Ruby, everything is true, except nil and false . Therefore:

"olá".to_b => true
0.to_b     => true
"".to_b    => true
true.to_b  => true
nil.to_b   => false
false.to_b => false
    
27.12.2017 / 04:09