Skip to content
loading...

re: #to_s or #to_str? Explicitly casting vs. implicitly coercing types in Ruby VIEW POST

FULL DISCUSSION
 

I believe it’s worth it to mention the generic coerce method and how the coercion might be done for generic classes. Like:

class NumberWrapper
  def initialize(number)
    raise(ArgumentError, 'Numeric is expected') unless Numeric === number
    @number = number
  end

  def +(other)
    @number + other
  end

  def coerce(other)
    [self, other]
  end
end

The above makes it possible to use the instances of this class anywhere in the operator chain (despite Numeric#+ knows nothing about how to deal with our class instances):

3 + NumberWrapper.new(5) + 3
#⇒ 11
code of conduct - report abuse