kehtyr kehtyr - 11 months ago 65
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

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

ndn ndn
Answer Source

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

class TrueClass
  def to_i

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

1 * true # => 1

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