创建一个在Ruby中使用额外参数的setter方法

Val*_*lea 18 ruby methods setter indexer

我正在尝试编写一个充当setter的方法,除了赋值之外还需要一些额外的参数.愚蠢的例子:

class WordGenerator
  def []=(letter, position, allowed)
    puts "#{letter}#{allowed ? ' now' : ' no longer'} allowed at #{position}"
  end

  def allow=(letter, position, allowed)
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)

把它写成索引器是有效的,我可以像这样调用它:

gen = WordGenerator.new

gen['a', 1] = true
# or explicitly:
gen.[]=('a', 1, true)
Run Code Online (Sandbox Code Playgroud)

但当我尝试以下任何一种情况时,口译员会抱怨:

gen.allow('a', 1) = false # syntax error
gen.allow=('a', 1, false) # syntax error
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用,我错过了显而易见的事吗?

sep*_*p2k 19

它不起作用,因为解析器不允许它.等号是允许在形式的表达式identifier = expression,expression.identifier = expression(其中,标识符是\w+),expression[arguments] = expressionexpression.[]= arguments作为一个字符串文字或符号或字符的一部分(和?=).而已.

gen.send(:allow=, 'a', 1, false)会工作,但在那时你也可以给该方法一个不包括a的名称=.


小智 6

我遇到过这个并决定将我的参数作为数组或哈希传递.

例如:

def allow=(arguments)
  puts arguments[:letter]
  puts arguments[:position]
  puts arguments[:allowed]
end

object.allow={:letter=>'A',:position=>3,:allowed=>true}
Run Code Online (Sandbox Code Playgroud)