How to convert any method to infix operator in ruby

后端 未结 4 1314
陌清茗
陌清茗 2020-12-20 03:40

In some language such as Haskell, it is possible to use any function taking two arguments as an infix operator.

I find this notation interesting and would like to ac

4条回答
  •  星月不相逢
    2020-12-20 04:44

    Based on Wayne Conrad's answer, I can write the following code that would work for any method defined in ruby top-level:

    class Object
      def method_missing(method, *args)
        return super if args.size != 1
        # only work if "method" method is defined in ruby top level
        self.send(method, self, *args)
      end
    end
    

    which allows to write

    def much_greater_than(a,b)
      a >= b * 10
    end
    
    "A very long sentence that say nothing really but should be long enough".much_greater_than "blah"
    
    # or
    
    42.much_greater_than 2
    

    Thanks Wayne!

    Interesting reference on the same subject:

    • Defining a new logical operator in Ruby

提交回复
热议问题