Ruby Methods and Optional parameters

后端 未结 11 1612

I\'m playing with Ruby on Rails and I\'m trying to create a method with optional parameters. Apparently there are many ways to do it. I trying naming the optional parameters

11条回答
  •  盖世英雄少女心
    2020-12-13 09:58

    To answer the question of "why?": the way you're calling your function,

    my_info "Bill", age: 99, weight: 300, city: "Sao Paulo"
    

    is actually doing

    my_info "Bill", {:age => 99, :weight => 300, :city => "Sao Paulo"}
    

    Notice you are passing two parameters, "Bill" and a hash object, which will cause the default hash value you've provided in my_info2 to be completely ignored.

    You should use the default value approach that the other answerers have mentioned.

提交回复
热议问题