> So it's good practice to use symbols to reference "things" in your
> program. This is why symbols make good keys in hashes since the keys  
> in
> hashes are generally used to identify things in the hash and the  
> actual
> characters are not as important.

But, pay attention to the API for the library you are using.  They  
don't always accept a symbol -- some expect a string.  They'll do  
something like this:

case passed_in_argument
when "foo" then ...
when "bar" then ...
end

If you pass in :foo for the argument it won't match.

Now that said, most of Rails runs stringify_keys on the arguments so  
it's a non issue.  Not all the plugins do. Just something to watch out  
for if your symbol isn't doing what you expected it to do.

> Example:
> attributes = { :name => "William", :occupation => "Programmer" }
> puts attributes[:name]
> => "William"
>
> Read attributes[:name] as, "Get me the thing referenced by :name from
> attributes." The actual characters in the symbol :name don't really
> matter it could have been called :xyz and it would still mean the same
> thing { :xyz => "William" }; attributes(:xyz) => "William".
>
> Now imagine what would happen if strings were used as keys:
>
> a = { 'name' => "William", 'occupation' => "Programmer" }
> b = { 'name' => "Steve", 'occupation' => "Project Manager" }
>
> In this case there would be four separate String instances to  
> represent
> the same keys (same string of characters 'name' and 'occupation' but
> when symbols are used for keys only two symbols are created :name and
> :occupation. Each occurrence of each symbol, no matter how many hashes
> exist, are only stored in memory once. So even if a thousand hashes  
> use
> the symbol :name the symbol would only take up memory once on its  
> first
> usage.

I thought I'd read somewhere though that a symbol once created is  
never destroyed so it takes up space in RAM.  A string will be  
destroyed once it goes out of scope.  The take away being that if you  
create a thousand symbols but only use them once you're going to be  
eating up a lot of RAM. An edge case maybe as typically you'll use the  
symbol many times, but something to keep an eye on.

Someone please correct me if I'm wrong about the symbol/ram/usage issue.

-philip

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to