0

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 !

ndjerrou
  • 1
  • 1
  • _"units does a reference to a specified argument called units"_ – you can't really tell whether this is a keyword argument or a hash. Ruby 2.x transparently converts between them, so `foo(a: 1)` and `foo({a: 1})` are effectively the same. Ruby 3.x is going to have "real" keyword arguments. – Stefan Dec 11 '18 at 11:19
  • The answers down below explain the symbol syntactic sugar. For the difference between when to use a string as key and when to use a symbol as key I recommend checking out [*When to use symbols instead of strings in Ruby?*](https://stackoverflow.com/questions/16621073/when-to-use-symbols-instead-of-strings-in-ruby). – 3limin4t0r Dec 11 '18 at 15:50

2 Answers2

1
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.

Ursus
  • 29,643
  • 3
  • 33
  • 50
1

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}" }

ray
  • 5,454
  • 1
  • 18
  • 40
  • 1
    _"nothing but simplified convention in rails"_ – this isn't Rails specific, Rails cannot alter Ruby's syntax. – Stefan Dec 11 '18 at 11:24