when to use * arguments?

Z

Zhenning Guan

version one:

def say(*a)
a.each {|r| puts r }
end

say(1,2,3)
------

version two:

def say(a)
a.each {|r| puts r }
end

say([1,2,3])
 
I

Iñaki Baz Castillo

El Viernes, 8 de Enero de 2010, Zhenning Guan escribi=C3=B3:
version one:
=20
def say(*a)
a.each {|r| puts r }
end
=20
say(1,2,3)
------
=20
version two:
=20
def say(a)
a.each {|r| puts r }
end
=20
say([1,2,3])

* is useful when you don't know the number and kind of arguments the method=
=20
will receive. Using * will convert any arguments to an Array.

In your first version:

irb> say 123
123
[123] <-- returns an Array

In your second version:

irb> say 123
NoMethodError: undefined method `each' for 2:Fixnum
from (irb):6:in `say'
=20


=2D-=20
I=C3=B1aki Baz Castillo <[email protected]>
 
B

Bertram Scharpf

Hi,

Am Freitag, 08. Jan 2010, 18:43:41 +0900 schrieb Zhenning Guan:
version one:
def say(*a)
a.each {|r| puts r }
end
say(1,2,3)

version two:
def say(a)
a.each {|r| puts r }
end
say([1,2,3])
So, any different here? when should we * arguments like version one?

Sometimes you have to use splats: when you call another method and
you don't know what arguments that one takes. Object.new does this
internally. It's something like

class Object
class <<self
def new *args
instance = allocate_space
instance.initialize *args # <<<
instance
end
end
end

Bertram
 
S

Sebastian Hungerecker

It's something like

class Object
class <<self
def new *args
instance = allocate_space
instance.initialize *args # <<<
instance
end
end
end

To nitpick (I know it isn't relevant to the discussion at hand), it's
actually
more something like:

class Class # instance method of Class, not singleton method of Object
def new *args, &blk # Can take (and will pass) a block, too
# Calls Class#allocate (or a particular class's override of that
method)
instance = allocate
instance.send:)initialize, *args, &blk) # initialize is a private
method
instance
end
end

Except, of course, it's written in C.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,160
Messages
2,570,890
Members
47,423
Latest member
henerygril

Latest Threads

Top