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
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.