Influence of ":" in Ruby

Asked

Viewed 88 times

3

The Framework data validation parameters Ruby on Rails, 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 they work and what kind of value they are?

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

Note: The question is not intended to compare a String "texto" with a symbol for a String :texto, and yes with the symbols :valor and valor:.

1 answer

7


Values starting with : are Symbols. Symbol is a data type, just like String, Integer, Array and etc. Symbols with the same name will always have the same Object ID and thus point to the same memory location. This makes them more effective than strings for use as a hash key, etc.

As for the values within { }, with : after the name, they are keys of a hash. { e } delimit the beginning and end of a hash. Each hash item 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', :other_key => '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, are explicit.

See some tutorials about:

http://guru-sp.github.io/tutorial_ruby/simbolos.html

http://www.akitaonrails.com/2007/11/26/ruby-symbols

Browser other questions tagged

You are not signed in. Login or sign up in order to post.