InQusitive InQusitive - 10 months ago 38
Ruby Question

What are those x: identifiers called in rails?

When do we use a colon after an identifier in ruby? for eg:

<%= f.input :XML, as: :file, wrapper: :vertical_file_input %>

here we have
but for
we don't have a colon.

What are those
identifiers known as? and how do we decide whether to put a colon or not?

Answer Source

It's just syntactic sugar.

{as: :file, wrapper: :vertical_file_input}

is a Hash, equal to

{:as=>:file, :wrapper=>:vertical_file_input}

I personally don't find the first version more readable.

So x: is just :x (a Symbol) as key in a hash.

f.input :XML, as: :file, wrapper: :vertical_file_input

is the method "input" called on object f, with :XML as first parameter and {:as=>:file, :wrapper=>:vertical_file_input} as second parameter. You could also write it :

f.input(:XML, {as: :file, wrapper: :vertical_file_input})

This kind of method call is very common in Rails.