2

In Python I can determine the boolean value an expression evaluates to if I use the bool function. For example:

bool(1)
#=> True

Does such a construct exist in Ruby? I can't seem to find evidence that it does. I'm currently having to use equivalence tests to determine boolean values and was wondering if there was more a convenient way of doing this.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
seeker
  • 530
  • 1
  • 4
  • 14
  • 3
    Which values in Ruby would you expect to evaluate to `true` and which to `false`? Ruby and Python don't agree on this question (consider not just `0`, but the empty string, array, range, etc.), so if you want something that behaves like Python you'll need to write it yourself. – Jordan Running May 22 '19 at 20:11
  • 2
    https://stackoverflow.com/q/3028243/1126841 may be relevant. – chepner May 22 '19 at 20:12
  • I wonder if `bool(1) #=> true` implies that you would expect `bool(0) #=> false`? What is `true` or `false`? What is the expected output or other inputs? Can you please elaborate on this? – spickermann May 22 '19 at 20:14
  • Take a look at https://stackoverflow.com/a/35092232/128421 for a breakdown of how we look at Ruby truth/false. – the Tin Man May 22 '19 at 23:43

3 Answers3

9

There's always the classic

!!a

This also works in Javascript, C++, and (using not instead of !) Python.

Bear in mind that Ruby has different notions of truthiness than Python. In Python, a lot of "empty" objects are falsy, and custom classes can have their truthiness determined by a magic method. In Ruby, only nil and false are falsy, and all other values (including numbers, strings, lists, and any user-defined class) are truthy.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
3

If what you want is to 1 == true and 0 == false, you should explicitly compare the values, such as:

if x == 1
  # do something
end

That's because, in Ruby, only false and nil are falsy. The rest evaluates to true.

In other words:

def to_bool(x)
  !!x
end

to_bool(1)          #=> true
to_bool(0)          #=> true
to_bool("0")        #=> true
to_bool("1")        #=> true
to_bool(Object.new) #=> true

to_bool(nil)        #=> false
vinibrsl
  • 6,563
  • 4
  • 31
  • 44
3

If you know which type you'll use, you could try to mimick Python's logic in Ruby.

An empty list, hash or string are truthy in Ruby, so you'll need to check if they're not empty:

![].empty?
# => false
![3].empty?
# => true
!"".empty?
# => false
!"foo".empty?
# => true

Likewise, you could check that an integer is not zero:

0 != 0
#=> false
1 != 0
#=> true
3.14 != 0
#=> true
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124