Answer the question
In order to leave comments, you need to log in
Why does Rails use symbols (Symbol) as object property names?
My guess is that many ActiveRecord models might have the same properties, such as "title" or "id", and then using the characters (:title, :id) to name the properties would save memory. If so, is this a strict rule or convention?
I'm new to Ruby and RoR, and after many years with PHP and IBM Lotus, I feel like I'm in heaven) But understanding some things (eg, symbols and rail internals) is still not easy.
Thanks for the replies.
Answer the question
In order to leave comments, you need to log in
Symbols are analogous to simple strings, but differ from them in that they occupy a permanent place in memory. That is, if you make a hash {'title' => 'There is no spoon'}
, then 'title'
each time it will take a new place in memory. On the other hand, in a hash of the form, {title: 'There is no spoon'}
the character :title
will occupy the same position in memory each time. It is easy to conclude that the use of symbols saves memory when the program is running.
Line example:
2.1.5 :004 > 'title'.object_id
=> 70319227477100
2.1.5 :005 > 'title'.object_id
=> 70319227461020
2.1.5 :006 > 'title'.object_id
=> 70319227447980
2.1.5 :007 > 'title'.object_id
=> 70319227431260
2.1.5 :008 > :title.object_id
=> 1145928
2.1.5 :009 > :title.object_id
=> 1145928
2.1.5 :010 > :title.object_id
=> 1145928
2.1.5 :011 > :title.object_id
=> 1145928
2.1.5 :013 >
{key: 'value'}
(before 1.9 it was like this: {:key => 'value'}
). Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question