How can I properly chain custom methods in Ruby?

后端 未结 4 2004
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 10:49

I am trying to do a chaining method for the following two methods. After running this code, I kept getting the following output:

#

        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 11:15

    Are you trying to do something like this?

    class SimpleMath
      def initialize
        @result = 0
      end
    
      #1 add function
      def add(val)
        @result += val
        self
      end
    
      #2 Subtract function
      def subtract(val)
        @result -= val
        self
      end
    
      def to_s
        @result
      end
    end
    
    newNumber = SimpleMath.new
    p newNumber.add(2).add(2).subtract(1)
    

    For any number of arguments

    class SimpleMath
      def initialize
        @result = 0
      end
    
      #1 add function
      def add(*val)
        @result += val.inject(&:+)
        self
      end
    
      #2 Subtract function
      def subtract(*val)
        @result -= val.inject(&:+)
        self
      end
    
      def to_s
        @result
      end
    end
    
    newNumber = SimpleMath.new
    p newNumber.add(1, 1).add(1, 1, 1, 1).subtract(1)
    

提交回复
热议问题