How are symbols used to identify arguments in ruby methods

后端 未结 5 1131
星月不相逢
星月不相逢 2021-02-01 23:20

I am learning rails and going back to ruby to understand how methods in rails (and ruby really work). When I see method calls like:

validates :first_name, :presen         


        
5条回答
  •  情歌与酒
    2021-02-01 23:36

    I thought I'd add an update for Ruby 2+ since this is the first result I found for 'symbols as arguments'.

    Since Ruby 2.0.0 you can also use symbols when defining a method. When calling the method these symbols will then act almost the same as named optional parameters in other languages. See example below:

    def variable_symbol_method(arg, arg_two: "two", arg_three: "three")
      [arg, arg_two, arg_three]
    end
    
    result = variable_symbol_method :custom_symbol, arg_three: "Modified symbol arg"
    
    # result is now equal to:
    [:custom_symbol, "two", "Modified symbol arg"]
    

    As shown in the example, we omit arg_two: when calling the method and in the method body we can still access it as variable arg_two. Also note that the variable arg_three is indeed altered by the function call.

提交回复
热议问题