In Ruby, how does coerce() actually work?

后端 未结 2 1987
栀梦
栀梦 2020-11-30 20:12

It is said that when we have a class Point and knows how to perform point * 3 like the following:

class Point
  def initialize(x,y)         


        
2条回答
  •  醉话见心
    2020-11-30 20:52

    I find myself often writing code along this pattern when dealing with commutativity:

    class Foo
      def initiate(some_state)
         #...
      end
      def /(n)
       # code that handles Foo/n
      end
    
      def *(n)
        # code that handles Foo * n 
      end
    
      def coerce(n)
          [ReverseFoo.new(some_state),n]
      end
    
    end
    
    class ReverseFoo < Foo
      def /(n)
        # code that handles n/Foo
      end
      # * commutes, and can be inherited from Foo
    end
    

提交回复
热议问题