How can I get a reference to a method?

前端 未结 4 497
花落未央
花落未央 2021-01-07 16:32

Is it possible in Ruby to get a reference to methods of an object ( I would like to know if this can be done without procs/lambdas ) , for example , consider the following c

4条回答
  •  温柔的废话
    2021-01-07 17:10

    Ruby methods aren't first-class objects; it implements OO with message passing.

    class X
      def call(a)
        self.send(:a, a) if a > 10
        self.send(:b, a) if a > 20
        self.send(:c, a) if a > 30
      end
    
      def a(arg)
         puts "a was called with #{arg}"
      end
    
      def b(arg)
         puts "b was called with #{arg}"
      end
    
      def c(arg)
        puts "c was called with #{arg}"
      end
    end
    

    Or just call them directly:

    def call(a)
      self.a(a) if a > 10
      self.b(a) if a > 20
      self.c(a) if a > 30
    end
    

提交回复
热议问题