kehtyr kehtyr - 2 months ago 10
Ruby Question

to_int: how to allow coerce of TrueClass into Fixnum

I tried extending the Boolean classes like so:

class TrueClass def to_i() 1 end end
class TrueClass def to_int() 1 end end

class FalseClass def to_i() 0 end end
class FalseClass def to_int() 0 end end


But
1 * true
still throws
true can't be coerced into Fixnum

ndn ndn
Answer

Read the article in the comment, tl;dr would be:

class TrueClass
  def to_i
    1
  end

  def coerce(other)
    [other, other.is_a?(Numeric) ? to_i : self]
  end
end

1 * true # => 1

If you want to do arithmetic with booleans only, you may remove the conditional, but this might have side effects.

Comments