ndjerrou
ndjerrou

Reputation: 1

Confusion between hashes and symbols

May you help me understand the concept behind the hash and especially when we use symbols.

:name is a symbol right ?

we can use symbol as a key for our hashed right ?

:name and name: for example : those are two syntaxes but it describes a symbol right ?

when we have this for example :

Geocode.configure(

units: :km

)

here units does a reference to a specified argument called units in the configure function right ? and :km is the symbol we want to send through the variable unit or am I wrong ?

A last example :

validates :home_type, presence: true

Here we try to send to the validates function the symbol home_type right ?

and the second argument is named "presence" and we want to send the boolean true through this variable right ?

I am sorry if you don't understand my question, don't hesitate to ask me.

I got many headeck nderstanding those syntaxes.

Thanks a lot !

Upvotes: 0

Views: 100

Answers (2)

ray
ray

Reputation: 5552

It is very basic & nothing but simplified convention in ruby

validates :home_type, presence: true, if: :check_user

is similar to

validates :home_type, { :presence => true, :if => :check_user }

So when I write as,

link_to 'Edit', edit_path(user), class: 'user_one', id: "user_#{user.id}"

In above, link_to is ActionHelper method which is taking 3 arguments where last one is hash { class: 'user_one', id: "user_#{user.id}" }

Upvotes: 1

Ursus
Ursus

Reputation: 30056

Geocode.configure(units: :km)

We are passing an hash to the configure method. This hash {units: :km}. Convenient syntax for {:units => :km}. So an hash with a key value pair with key symbol (:units) and value symbol (:km).

validates :home_type, presence: true

Here we are passing to the validates method a symbol :home_type and an hash, {presence: true}, or {:presence => true}. So the key is :presence symbol, the value is the boolean true.

Upvotes: 1

Related Questions