在Ruby中创建一个需要额外参数的setter方法 [英] Creating a setter method that takes extra arguments in Ruby
问题描述
我正在尝试编写一种充当设置器的方法,该方法除了分配的值外还接受一些额外的参数.愚蠢的例子:
I'm trying to write a method that acts as a setter and takes some extra arguments besides the assigned value. Silly example:
class WordGenerator
def []=(letter, position, allowed)
puts "#{letter}#{allowed ? ' now' : ' no longer'} allowed at #{position}"
end
def allow=(letter, position, allowed)
# ...
end
end
将其写为索引器是可行的,我可以这样称呼它:
Writing it as an indexer works and I can call it like this:
gen = WordGenerator.new
gen['a', 1] = true
# or explicitly:
gen.[]=('a', 1, true)
但是当我尝试以下任何一种方法时,口译员都会抱怨:
But when I try any of the following, the interpreter complains:
gen.allow('a', 1) = false # syntax error
gen.allow=('a', 1, false) # syntax error
为什么不起作用,我错过了明显的地方吗?
Why won't this work, am I missing the obvious?
推荐答案
它不起作用,因为解析器不允许.在形式为identifier = expression
,expression.identifier = expression
(其中标识符为\w+
),expression[arguments] = expression
和expression.[]= arguments
的表达式中,以及作为字符串,符号或字符文字(?=
)的一部分,均允许使用等号.就是这样.
It doesn't work because the parser doesn't allow it. An equals sign is allowed in expressions of the form identifier = expression
, expression.identifier = expression
(where identifier is \w+
), expression[arguments] = expression
and expression.[]= arguments
and as part of a string or symbol or character literal (?=
). That's it.
gen.send(:allow=, 'a', 1, false)
可以工作,但是那时候您也可以给该方法指定一个不包含=
的名称.
gen.send(:allow=, 'a', 1, false)
would work, but at that point you could as well just give the method a name that doesn't include a =
.
这篇关于在Ruby中创建一个需要额外参数的setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!