Forum: Ruby Simple Question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Joe B. (Guest)
on 2008-11-15 22:57
I saw the following in a book.

def deleted_roles=(values)
  roles.find(*values).each(&:destroy)
end

I understand that this method finds all the roles with the given ids and
calls destroy on all of them. My question is, what is the significance
of *. Why is it roles.find(*values) and not just plain
roles.find(values)?

Is there any difference?

Could it possibly be a typo and the method should be defined as

def deleted_roles(*values)...

Thanks
Serabe (Guest)
on 2008-11-15 23:12
(Received via mailing list)
* expands an array as multiple arguments. For example, type in an irb
session:

def find(*args) # This * is not the same * as yours, this is just used
to collect all the arguments in a single array
  args.each {|x| puts x.class}
end

find [1,2,3] => Array
find *[1,2,3] => Fixnum three times.

Regards,

Serabe
Peter S. (Guest)
on 2008-11-15 23:19
(Received via mailing list)
Hi,

> Is there any difference?
>
> Could it possibly be a typo and the method should be defined as
>
> def deleted_roles(*values)...

It looks like roles.find expects a list of parameters (i.e. it should
be invoked like this: roles.find('admin', 'user', 'editor'))
but deleted_roles= wants an array (i.e. deleted_rows = ['admin',
'user', 'editor'])

The * a.k.a.  splat does exactly this conversion - so if someone calls

deleted_rows = ['admin', 'user', 'editor']

inside the method

  roles.find('admin', 'user', 'editor').each(&:destroy)

will be called (note that the brackets are gone)


HTH,
Peter
___
http://www.rubyrailways.com
This topic is locked and can not be replied to.