How are symbols used to identify arguments in ruby methods

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

    Symbols are not limited to hashes. They are identifiers, without the extra storage space of a string. It's just a way to say "this is ...."

    A possible function definition for the validates call could be (just to simplify, I don't know off the top of my head what it really is):

    def validates(column, options)
       puts column.to_s
       if options[:presence]
         puts "Found a presence option"
       end
     end
    

    Notice how the first symbol is a parameter all of its own, and the rest is the hash.

提交回复
热议问题