Is it a variable Symbol, a method, why does it have a colon, but it doesn't?

Inconsistent naming conventions in Rails confuse me. The syntax seems to be everywhere. Here are some examples:

Why are there commas in the link below? And why doesn't the default keyword have a colon before it? What is the default keyword, method or variable, symbol? What is it?:

 add_column :zombies, :rotting, :boolean, default: false 

Here is another example:

Why is age not :age (with a colon)? Why is make_rotting called with a " : " before this?

  class Zombie < ActiveRecord::Base before_save :make_rotting def make_rotting if age > 20 self.rotting = true end end end 
+4
source share
2 answers

Ruby can be difficult for people of Java and PHP. :)

In Ruby, not everything looks as it seems. Take this for example:

 before_save :make_rotting 

This is a method call, of course. But this is not the make_rotting method that is called. This is before_save ( :make_rotting is its parameter). This is the so-called “hook” in ActiveRecord. before_save will take the method name as a parameter and will dynamically call it when the time comes.

 if age > 20 

Here age is a method call, not a character. It can be written as:

 if age() > 20 

but brackets are optional. And finally:

 add_column :zombies, :rotting, :boolean, default: false 

This method takes four parameters, the last of which is a hash. The hash uses the new Ruby 1.9 syntax. Previously, it would be written like this (with a colon in the right place and that's it):

 add_column :zombies, :rotting, :boolean, :default => false 

You should read a good Ruby programming book, instead of scraping pieces of knowledge from Stack Overflow posts. :)

+8
source

Three main things:

  • Methods in Ruby do not require parentheses around their arguments. before_save and add_column are methods, therefore :make_rotting is an argument to before_save .
  • Everything starting with the : character is a character. Characters are like strings, but they are allocated only in memory, regardless of how many times you use the same character in your code. They are used for many things - very often, like hash keys.
  • Ruby methods that take a hash as the last argument do not require {} around the hash.

So this is:

 add_column :zombies, :rotting, :boolean, default: false 

can be rewritten as:

 add_column(:zombies, :rotting, :boolean, {default: false}) 
+3
source

Source: https://habr.com/ru/post/1441849/


All Articles