Named parameters in Ruby 2

后端 未结 8 1779
闹比i
闹比i 2020-12-13 13:28

I don\'t understand completely how named parameters in Ruby 2.0 work.

def test(var1, var2, var3)
  puts \"#{var1} #{var2} #{var3}\"
end

test(var3:\"var3-ne         


        
8条回答
  •  没有蜡笔的小新
    2020-12-13 13:46

    I think that the answer to your updated question can be explained with explicit examples. In the example below you have optional parameters in an explicit order:

    def show_name_and_address(name="Someone", address="Somewhere")
      puts "#{name}, #{address}"
    end
    
    show_name_and_address
    #=> 'Someone, Somewhere'
    
    show_name_and_address('Andy')
    #=> 'Andy, Somewhere'
    

    The named parameter approach is different. It still allows you to provide defaults but it allows the caller to determine which, if any, of the parameters to provide:

    def show_name_and_address(name: "Someone", address: "Somewhere")
      puts "#{name}, #{address}"
    end
    
    show_name_and_address
    #=> 'Someone, Somewhere'
    
    show_name_and_address(name: 'Andy')
    #=> 'Andy, Somewhere'
    
    show_name_and_address(address: 'USA')
    #=> 'Someone, USA'
    

    While it's true that the two approaches are similar when provided with no parameters, they differ when the user provides parameters to the method. With named parameters the caller can specify which parameter is being provided. Specifically, the last example (providing only the address) is not quite achievable in the first example; you can get similar results ONLY by supplying BOTH parameters to the method. This makes the named parameters approach much more flexible.

提交回复
热议问题