定义自定义Ruby运算符 [英] Define custom Ruby operator
问题描述
问题是:我可以在Ruby中定义我的自己的自定义运算符,除了在 "运算符"?
The question is: Can I define my own custom operator in Ruby, except for the ones found in "Operator Expressions"?
例如:1 %! 2
推荐答案
是的,尽管有一些注意事项,但可以创建自定义运算符. Ruby本身并不直接支持它,但是 superators gem 巧妙地将运算符链接在一起.这使您可以创建自己的运算符,但有一些限制:
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
然后:
require 'superators19'
class Array
superator "%~" do |operand|
"#{self} percent-tilde #{operand}"
end
end
puts [1] %~ [2]
# Outputs: [1] percent-tilde [2]
由于上述限制,我无法执行您的1 %! 2
示例. 文档包含完整的详细信息,但不能为Fixnums赋予上级者,而!
可以'不要成为超级管理员.
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.
这篇关于定义自定义Ruby运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!