[英]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. 我正在尝试编写一个充当setter的方法,除了赋值之外还需要一些额外的参数。 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? 为什么这不起作用,我错过了显而易见的事吗?
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 ( ?=
). 形式为identifier = expression
, expression.identifier = expression
(其中identifier为\\w+
), expression[arguments] = expression
和expression.[]= arguments
以及作为字符串或符号或字符的一部分的表达式中允许使用等号expression.[]= arguments
文字( ?=
)。 That's it. 而已。
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 =
. gen.send(:allow=, 'a', 1, false)
会的工作,但在这一点上,你可能也只是给方法不包括名称=
。
I have come across this and decided to pass my arguments as an array or hash. 我遇到过这个并决定将我的参数作为数组或哈希传递。
Eg: 例如:
def allow=(arguments)
puts arguments[:letter]
puts arguments[:position]
puts arguments[:allowed]
end
object.allow={:letter=>'A',:position=>3,:allowed=>true}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.