No named parameters in Ruby?

前端 未结 4 1252
日久生厌
日久生厌 2020-12-13 09:20

This is so simple that I can\'t believe it caught me.

def meth(id, options = \"options\", scope = \"scope\")
  puts options
end

meth(1, scope = \"meh\")

-&         


        
4条回答
  •  醉话见心
    2020-12-13 09:49

    Although named parameters are not supported by the Ruby language, you can simulate them by passing your function arguments through a hash. For example:

    def meth(id, parameters = {})
      options = parameters["options"] || "options"
      scope = parameters["scope"] || "scope"
    
      puts options
    end
    

    Which can be used as follows:

    meth(1, scope: "meh")
    

    Your existing code simply assigns a varaible, then passes that variable to your function. For more information see: http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html.

提交回复
热议问题