@Casper is right. Only one of the parameters can have the splat operator. Arguments get assigned to the non-splatted parameters first left-to-right. Remaining arguments get assigned to the splat parameter.
You can do as he suggest. You can also do this:
def test(id,h={},*a)
# do something with id
# if not h.empty? then do something with h end
# if not a.empty? then do something with a end
end
Here are some sample irb runs:
001 > def test (id, h={}, *a)
002?> puts id.inspect
003?> puts h.inspect
004?> puts a.inspect
005?> end
=> nil
006 > test(1,2,3,4)
1
2
[3, 4]
=> nil
007 > test(1,{"a"=>1,"b"=>2},3,4)
1
{"a"=>1, "b"=>2}
[3, 4]
=> nil
008 > test(1,nil,3,4)
1
nil
[3, 4]
=> nil
Perhaps, I should add. You CAN have an optional parameter as the last parameter but it must be a block/proc.
For example:
def test(a,*b, &c)
puts a.inspect
puts b.inspect
c.call if not c.nil?
end
Here are some sample calls:
006 > test(1,2,3)
1
[2, 3]
=> nil
007 > test(1,2,3) {puts "hello"}
1
[2, 3]
hello
=> nil
test(id, hash1)
, are you expectingary = [hash1]; hash = nil
orary = []; hash = hash1
? What is the rule that determines whichever to choose? – Foumart