使用作为参数时的"*"的含义(不像*arg,只是*)

Tak*_*chi 8 ruby ruby-on-rails

当我阅读Rails代码时,我发现了这一点

def save(*)
  create_or_update || raise(RecordNotSaved)
end
Run Code Online (Sandbox Code Playgroud)

怎么*办?:O我知道当我们使用它时会发生什么*args,但在这种情况下,它很简单*.

参考https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb#L119

Jör*_*tag 8

它与使用参数名称时的含义相同:吞噬所有剩余的参数.除了,因为没有名称将它们绑定到,所以参数是不可访问的.换句话说:它需要任意数量的参数但忽略它们.

请注意,实际上一种方法可以使用参数:当您在super没有参数列表的情况下调用时,参数将按原样转发到超类方法.


Lea*_*ner 2

在这种特定情况下,保存不接受任何参数。这就是赤裸裸的泼溅所发生的情况。但是,您可能知道,在ActiveRecord模型上调用 save 会接受选项,因为此方法会被ActiveRecord::Validations此处覆盖:

https://github.com/rails/rails/blob/v3.1.3/activerecord/lib/active_record/validations.rb#L47

# The validation process on save can be skipped by passing <tt>:validate => false</tt>. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
 perform_validations(options) ? super : false
end
Run Code Online (Sandbox Code Playgroud)