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?
version one:
def say(*a)
a.each {|r| puts r }
end
version two:
def say(a)
a.each {|r| puts r }
end
So, any different here? when should we * arguments like version one?
El Viernes, 8 de Enero de 2010, Zhenning G. escribió:
def say(a)
a.each {|r| puts r }
endsay([1,2,3])
So, any different here? when should we * arguments like version one?
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’
Hi,
Am Freitag, 08. Jan 2010, 18:43:41 +0900 schrieb Zhenning G.:
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
On 08.01.2010 13:00, Bertram S. wrote:
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs