How are symbols used to identify arguments in ruby methods

后端 未结 5 1123
星月不相逢
星月不相逢 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:47

    In Ruby, if you call a method with a bunch of name => value pairs at the end of the argument list, these get automatically wrapped in a Hash and passed to your method as the last argument:

    def foo(kwargs)
      p kwargs
    end
    
    >> foo(:abc=>"def", 123=>456)
    {:abc=>"def", 123=>456}
    
    >> foo("cabbage")
    "cabbage"
    
    >> foo(:fluff)
    :fluff
    

    There's nothing "special" about how you write the method, it's how you call it. It would be perfectly legal to just pass a regular Hash object as the kwargs parameter. This syntactic shortcut is used to implement named parameters in an API.

    A Ruby symbol is just a value as any other, so in your example, :first_name is just a regular positional argument. :presence is a symbol used as a Hash key – any type can be used as a Hash key, but symbols are a common choice because they're immutable values.

提交回复
热议问题