What do these weird characters mean?

我的梦境 提交于 2019-12-24 05:57:12

问题


I'm reading a Ruby book but it doesn't explain the following:

  1. What is this: validates :name, :presence => true

    • I mean I know what it does but what's validates? Is it a method of the validator class? If so, how come it's called without mentioning the class name first?

    • What's the meaning of : in the previous code and in Rails on general?

  2. In the following code: <%= form_for([@post, @post.comments.build]) do |f| %>

    • Is form_for an object or a procedural function?

    • What's the meaning of the | character in |f|

  3. In <%= link_to 'Edit Post', edit_post_path(@post) %>

    • Who, where and when was edit_post_path method defined?

    • To which class it belongs?


回答1:


  1. validates is a method, part of the validators in Rails. It is declared in (actually, included to) a superclass, that is why it does not have to be declared in the model. The : in front of anything signifies a symbol, not a variable. Symbols are part of Ruby, somewhat similar to strings.
  2. form_for is a method, which takes a number of parameters and a block (that is why there is a do afterwards). The | is part of Ruby syntax, the way you enclose code block parameters.
  3. edit_post_path is defined by the Rails magic and the routes. It is a helper method.

I encourage you to read this book about Ruby to get more familiar with symbols, code blocks, modules and other things that make Ruby a great programming language.



来源:https://stackoverflow.com/questions/6185497/what-do-these-weird-characters-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!