可以用 ... =
格式定义方法,如下所示:
class A
def f= x
puts x
end
end
A.new.f = 5
但是是否可以用这种格式定义一个带有参数的方法,以便可以像下面这样使用它?
A.new.f(a, b, c) = 5
编辑
您可以使用[]=
来做到这一点
class A
def []= x, y, z
puts x, y, z
end
end
A.new[1, 2] = 3
这是一个特例吗?
最佳答案
A.new.f(a, b, c) = 5
是语法错误,所以肯定不是(这也没有意义;)
[]
只是 .send(:[]=, ...) 的糖,它只是具有奇特名称的 setter。
您可以使用多个参数定义setter,但使用它的唯一方法是
A.new.send(:f=, "第一", "第二")
因为解析器不允许像 A.new.foo = "first", "second"这样的语法。
关于ruby - 定义带参数的 `... = `类型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12561404/