Can be some method added to Ruby object to achieve automatic conversion to boolean? E.g. if obj == true
Asked
Active
Viewed 1,809 times
1

azrael
- 263
- 3
- 13
-
1What are the rules for the conversion? Which objects should be converted to `true` and which to `false`? – Stefan Sep 01 '16 at 12:04
-
"Double bang" is usually used for this (`!!obj`). See: http://stackoverflow.com/questions/3994033/ruby-operator-a-k-a-the-double-bang – Bart Sep 01 '16 at 12:08
2 Answers
1
==
is a syntax sugar for :==
method. You can define object's own :==
method, where you can specify, based on internal object's state, when the result of the comparision should be true
and when false
:
class SomeClass
def ==(val)
# specyfy the comparision behaviour
end
end
And then use it like:
sc = SomeClass.new
sc == true
=> true # or false, depending on :== method's implementation

maicher
- 2,625
- 2
- 16
- 27
0
Most of the time, you are going to check the truthyness of an object instead of converting it to a boolean explicitly. This is what happens of you just write
if obj
# here, obj is truethy
else
# here, object is falsey
end
In Ruby, only false
and nil
are defined as falsey. All other objects are truethy. This can be used in conditions as shown above. Because of this, an explicit check for true
or false
is rather rare in Ruby.
That said, if you do want to convert an object to a boolean based on its truthyness value, you can use the double-negation, i.e.
obj_truthyness = !!obj
# => true or false

Holger Just
- 52,918
- 14
- 115
- 123
-
Thank you, but i want to implicitly convert object which is not nil. Boolean value depends on the internal state of the object and explicit conversion cannot be done (due to SASS). – azrael Sep 01 '16 at 12:08
-
I don't understand what you want to achieve. Please edit your original question and add some details to describe (1) what exactly you want to achieve, with actual examples (2) where this should be used and (3) why you need this. – Holger Just Sep 01 '16 at 12:32