The role of using key:value in Ruby function definition

The use of key=value and key:value for the parameters in the function definition in Ruby seems to be the same, but there are still big differences, especially when there is more than one parameter:

[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"]

 

Guess you like

Origin blog.csdn.net/TomorrowAndTuture/article/details/110876067