How can I properly chain custom methods in Ruby?

后端 未结 4 2005
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 11:12

    This fellow (tjackiw.tumblr.com) uses this as an interview question and gives a very clean walkthough of how & why the correct answer is similar to the following:

    class Interpreter
    
      def initialize(&block)
        instance_eval(&block)
      end
    
      def at(time)
        @time = time
        self
      end
    
      def when(date)
        @date = date
        self
      end
    
      def we(*people)
        @people = people
        self
      end
    
      def going(where)
        @where = where
        self
      end
    
      def output
        [@people.join(' and '), "are going", @where, @date, "at", @time].join(' ')
      end
    
    end
    

提交回复
热议问题