a = {1 => 'one',2=>'two'}
b = ['three','fore']
def show(x,y)
p x
p y
end
用这段代码来进行试验。
show(2,a)得:2
{1=>"one", 2=>"two"}
show(2,1 => 'one',2=>'two')得:2
{1=>"one", 2=>"two"}
show(2,b)得:
2
["three", "fore"]
show(2,'three','fore')得:1.rb:12:in `show': wrong number of arguments (3 for 2) (ArgumentError)
from 1.rb:12
show(a,2)得:
{1=>"one", 2=>"two"}
2
show(1 => 'one', 2=>'two')得:
1.rb:16:in `show': wrong number of arguments (1 for 2) (ArgumentError)
from 1.rb:16
show(1 => 'one',2=>'two',2)得:
1.rb:15: syntax error, unexpected ')', expecting tASSOC
show(1 => 'one',2=>'two',2)
^
由此可知,当hash作为参数时,只有在最后一个参数的位置传入时不会出错,并且会将若干hash对看成一个元素,所以我们在编程时尽量将hash参数放在最后面。
以上试验在1.8.6版本中进行。
本文通过实验展示了在编程中使用哈希作为参数时的正确方式与常见错误,强调了将哈希参数放置在调用函数参数末尾的重要性。
144

被折叠的 条评论
为什么被折叠?



