Influence of ":" in Ruby

3

The data validation parameters of the Ruby on Rails Framework use values with : before and after the word.

validates :terms_of_service, acceptance: { accept: true, message: 'Mensagem de Validação' }
validates :city, presence: true

How do they work and what kind of value are they?

What is the difference in : at the beginning and : at the end of the word?

  

Note: The question does not aim to compare a String % with_a% with a symbol to a String "texto" , but with symbols :texto and :valor .

    
asked by anonymous 01.07.2016 / 00:28

1 answer

7

Values that begin with: are symbols. Symbol is a data type, just like String, Integer, Array, and so on. Symbols with the same name will always have the same object ID and therefore point to the same memory location. This makes them more effective than strings for use as a key in hashes, etc.

As for values within {}, with: after the name, they are keys to a hash. {and} delimit the beginning and end of a hash. Each item in the hash is composed of a key and a value. In addition to the format {key: 'value', other_key: 'other value'}, hashes also use the syntax {: key => 'value',: otherkey => 'other value'}. In both hash examples, the keys are symbols. The difference is that in the first example, the: are implicit and, in the second example, they are explicit.

See some tutorials:

link

link

    
01.07.2016 / 01:15