Ruby 函数定义中使用 key:value 的作用

Ruby 中函数定义中参数使用 key=value 和 key:value 似乎是差不多的,但是其实还是有很大差异的,特别是有不止一个参数时:

[root@master ruby_learning]# cat test.rb
def test(host = HOST, port = PORT, index = 'jobs')
  puts [host, port, index].inspect
end

def test2(host = HOST, port = PORT, index: 'jobs')
  puts [host, port, index].inspect
end

HOST='localhost'
PORT='8200'
test(index='nice')
test(HOST, PORT, index='nice')
puts
test2(index:'nice')
test2(HOST, PORT, index:'nice')


[root@master ruby_learning]# ruby test.rb
["nice", "8200", "jobs"]
["localhost", "8200", "nice"]

["localhost", "8200", "nice"]
["localhost", "8200", "nice"]

猜你喜欢

转载自blog.csdn.net/TomorrowAndTuture/article/details/110876067