How to convert an object to Boolean in Ruby?

Asked

Viewed 434 times

1

Ruby objects have some methods for representation in another type, such as:

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

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

1 answer

1


The idiomatic way to convert an object of any type to Boolean in Ruby is by using a double negation (also called 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:

to_b "olá" => true
to_b 0     => true
to_b ""    => true
to_b true  => true
to_b nil   => false
to_b false => false
  • It would not be more appropriate to use to_b "olá" instead of "olá".to_b?

  • @Luizfelipe edited, thank you ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.