Jan Knezik Jan Knezik - 1 year ago 113
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 Source

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

And then use it like:

sc = SomeClass.new
sc == true
=> true # or false, depending on :== method's implementation
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download