ruby - 定义带参数的 `... = `类型方法

标签 ruby

可以用 ... = 格式定义方法,如下所示:

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/

相关文章:

ruby-on-rails - rails : ActiveRecord and send; how do I set an activerecord instance's relation with only knowing the class names?

ruby-on-rails - 从 If JSON 中拯救

ruby-on-rails - :autosave property of has_many associations broken in Rails 2. 3.4?

ruby-on-rails - "Could not find rake-0.9.2 in any of the sources"的根本原因是什么?

ruby-on-rails - 尝试从其他 Controller 模型检索数据时收到 ActiveRecord::RecordNotFound 消息

ruby db结果集到散列中的数组

ruby-on-rails - 为什么 RSpec 的方法 "get"、 "post"、 "put"、 "delete"在 gem(或 Rails 外部)的 Controller 规范中不起作用?

ruby-on-rails - 如何添加菜单注销 rails admin

ruby-on-rails - Rails : After putting devise routes in namespace, 模型名称以命名空间为前缀。如何删除它?

ruby - 请解释一下 ruby​​ 的这种元编程魔法