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?
--
Posted via http://www.ruby-forum.com/.
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?
* is useful when you don't know the number and kind of arguments the method
will receive. Using * will convert any arguments to an Array.
In your first version:
> say 123
123
[123] <-- returns an Array
In your second version:
> say 123
NoMethodError: undefined method `each' for 2:Fixnum
from (irb):6:in `say'
···
El Viernes, 8 de Enero de 2010, Zhenning Guan escribió:
--
Iñaki Baz Castillo <ibc@aliax.net>
Hi,
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
···
Am Freitag, 08. Jan 2010, 18:43:41 +0900 schrieb Zhenning Guan:
--
Bertram Scharpf
Stuttgart, Deutschland/Germany
*
Support `String#notempty?': <http://raa.ruby-lang.org/project/step>\.
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.
···
On 08.01.2010 13:00, Bertram Scharpf wrote:
It's something like
class Object
> class <<self
> def new *args
> instance = allocate_space
instance.initialize *args # <<<
> instance
> end
> end
> end