Hi,
I am a bit confused with ruby syntax with colon. You see
in controller “render :nothing => true”
and in routes " resources :books"
and in model “validates :name, :presence => true:”
everywhere so is that a key value pair or something else?
Hi,
I am a bit confused with ruby syntax with colon. You see
in controller “render :nothing => true”
and in routes " resources :books"
and in model “validates :name, :presence => true:”
everywhere so is that a key value pair or something else?
@venkata: Ruby makes a lot of things optional that other languages
require. It makes typing easier, but can lead to the very confusion you
encountered.
The first shorthand to know is that in Ruby, function and method calls
can omit the parentheses that bracket the arguments, so your examples:
render :nothing => true
resources :books
validates :name, :presence => true
are actually:
render(:nothing => true)
resources(:books)
validates(:name, :presence => true)
The second shorthand to remember is that in Ruby, if the last argument
to a function or method is a hash table, you can omit the enclosing {
}. So the examples are actually:
render({:nothing => true})
resources(:books)
validates(:name, {:presence => true})
And finally, any token that starts with a colon is a “symbol” – it acts
like a constant string. Symbols are especially useful as keywords,
which is why they’re often used as the key of a key/value pair in a hash
table.
So to describe each of your examples:
render is called with a hash table as its argument. the hash table
has a single key/value pair where the key is :nothing and the value is
true.
resources is called with a single keyword argument
validates is called with a keyword (:name) as its first argument and
a hash table as its second argument. the hash table has a single
key/value pair where the key is :presence and the value is true.
Hope this helps!
Very good explanation! Thank you very much…
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs