您的位置:首页 > 编程语言 > Ruby

Ruby中hash作为函数参数特殊性比较

2014-07-29 01:14 525 查看
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版本中进行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Ruby hash