Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The meaning of `*` when using as a param(not like *arg, just *) [duplicate]

When I was reading Rails code, I found this

def save(*)
  create_or_update || raise(RecordNotSaved)
end

What does the * do? :O I know what happens when we use it like *args, but in this case, it's just plain *.

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

like image 480
Takehiro Adachi Avatar asked Feb 18 '13 15:02

Takehiro Adachi


2 Answers

It means the same thing as it does when used with a parameter name: gobble up all the remaining arguments. Except, since there is no name to bind them to, the arguments are inaccessible. In other words: it takes any number of arguments but ignores them all.

Note that there actually is one way to use the arguments: when you call super without an argument list, the arguments get forwarded as-is to the superclass method.

like image 145
Jörg W Mittag Avatar answered Sep 28 '22 10:09

Jörg W Mittag


In this specific case, save doesn't take any arguments. That's what happens with a naked splat. But, as you may be aware, calling save on an ActiveRecord model accepts options because this method gets overridden by ActiveRecord::Validations here:

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
like image 42
Learner Avatar answered Sep 28 '22 10:09

Learner