Jan Knezik Jan Knezik - 3 months ago 14
Ruby Question

How to implicitly convert Ruby object to boolean

Can be some method added to Ruby object to achieve automatic conversion to boolean? E.g.

if obj == true

Answer

== 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