AlwaysCharging wrote:
> Is it that 'checkout' is passed a variable where empty_cart is not?
> Or, am I having bigger brain fart than that?
Here is a simple example that will hopefully illustrate the difference
between a symbol and a string:
$ irb
a = :foo
=> :foo
b = :foo
=> :foo
a.equal?(b)
=> true
c = 'foo'
=> "foo"
d = 'foo'
=> "foo"
c.equal?(d)
=> false
In this example notice that a is the same "thing" as b. But, c is NOT
the same "thing" as d. In other words in all case :foo refers to the
same instance (same thing) no matter how it's used. The variables c and
d reference two separate instances of strings containing the same three
characters ("foo").
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.
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.
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---