rubymethod-missing

Ruby "method_missing" Running a method once it was created


I'm trying to implement a code that automatically creates a method if it fits a certain keyword, with the help of method_missing.

This works so far:

class Add
    def initialize()
        @result = ""
    end


    def output()
        puts @result
     end

    def method_missing(name, *args)
        if name.to_s.include? "add"
            code = "def #{name}(*args)"\
            "@result << args.to_s;"\
            "end"
            instance_eval(code)
        end
    end
end

 a = Add.new

 a.add_1("1") #created but not called
 a.add_2("2") #created but not called
 a.add_2("2") #called
 a.output #I want it to return 122, but it returns only 2 once.

I want the method to run once it is created. This does not happen, as the method has to be called again before the code in it is executed.

How would I implement this?


Solution

  • As a starting point, perhaps something like this.

    class Add
      def initialize
        @result = ""
      end
    
      def output
        @result
      end
    
      def method_missing(name,arg)
        if name.to_s.include? 'add'
          @result << arg
          arg
        else
          super
        end
      end
    end
    
    a = Add.new
    
    p a.add '1'  # "1"
    p a.add '2'  # "2"
    p a.add '2'  # "2"
    p a.output   # "122"
    
    p a.minus '1' #NoMethodError