Define custom Ruby operator

后端 未结 3 1211
滥情空心
滥情空心 2020-12-10 17:57

The question is: Can I define my own custom operator in Ruby, except for the ones found in \"Operator Expressions\"?

For example: 1 %! 2

相关标签:
3条回答
  • 2020-12-10 18:33

    No. You can only define operators already specified in ruby, +,-,!,/,%, etc. (you saw the list)

    You can see for yourself this won't work

    def HI
      def %!
        puts "wow"
      end
    end
    

    This is largely due to the fact that the syntax parser would have to be extended to accept any code using your new operator.


    As Darshan mentions this example alone may not be enough to realize the underlying problem. Instead let us take a closer look at how the parser could possibly handle some example code using this operator.

    3 %! 0
    

    While with my spacing it may seem obvious that this should be 3.%!(0) without spacing it becomes harder to see.

    3%! can also be seen as 3.%(0.!) The parser has no idea which to chose. Currently, there is no way easy way to tell it. Instead, we could possibly hope to override the meaning of 3.%(0.!) but this isn't exactly defining a new operator, as we are still only limited to ruby's parsable symbols

    0 讨论(0)
  • 2020-12-10 18:41

    Yes, custom operators can be created, although there are some caveats. Ruby itself doesn't directly support it, but the superators gem does a clever trick where it chains operators together. This allows you to create your own operators, with a few limitations:

    $ gem install superators19
    

    Then:

    require 'superators19'
    
    class Array
      superator "%~" do |operand|
        "#{self} percent-tilde #{operand}"
      end
    end
    
    puts [1] %~ [2]
    # Outputs: [1] percent-tilde [2]
    

    Due to the aforementioned limitations, I couldn't do your 1 %! 2 example. The Documentation has full details, but Fixnums can't be given a superator, and ! can't be in a superator.

    0 讨论(0)
  • 2020-12-10 18:48

    You probably can't do this within Ruby, but only by modifying Ruby itself. I think modifying parse.y would be your best bet. parse.y famtour

    0 讨论(0)
提交回复
热议问题