S
S
Stepan Yudin2015-01-09 04:58:36
Ruby on Rails
Stepan Yudin, 2015-01-09 04:58:36

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

1 answer(s)
E
Eugene Burmakin, 2015-01-09
@stepan_sib

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 :titlewill 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

Symbol example:
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 >

Of course, the differences in memory usage may be minor, but that's just the way it is. In principle, this tradition can be considered an agreement. Well, it's worth mentioning that this convention turned out to be so popular that Ruby 1.9 introduced the ability to write hashes with characters as keys like this: {key: 'value'}(before 1.9 it was like this: {:key => 'value'}).
PS To understand Ruby read Programming Ruby 1.9 & 2.0, to understand Rails -- The Rails 4 Way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question