One reason to use Symbols is that they are immutable. When you’re
passing one around as an argument or Hash key, it won’t change.
Another is that multiple instances of a Symbol are the same object,
making a smaller memory footprint than Strings.
A string is not a symbol. Some structures will use to_s or to_sym to
allow you to pass either as an argument, but that’s not their default
behaviour.
On Friday, July 12, 2013 12:49:11 AM UTC-7, Ruby-Forum.com User wrote:
{‘a’=>1,:a=>2}
=> {“a”=>1, :a=>2}
{‘a’=>1,‘a’=>2}
=> {“a”=>2}
I know about this behavior, but this doesn’t answer the question I
posted.
I tested my question above.
I can create a hash in ruby and explicitly give it symbols for keys and
it
will work.
But when I retrieve a hash from a yml file, I cannot reference the keys
as
symbols.
yaml[‘config’] shows me the values from the yml file. yaml[:config]
doesn’t.
How else do you use symbols? I have read all the definitions. I
understand
the explanations, but the rest of where I am confused can now only be
answered by example usages.
Symbols are used all the time in Ruby/Rails when sending methods.
For example, look at the following method call:
instance.do_stuff(:foo => :bar, :answer => 3)
What you are actually sending to the do_stuff method is a hash that
looks
like the following:
{ :foo => :bar, :answer => 3 }
For these purposes, they are basically human-readable identifiers. The
advantage they have over strings in this case is that they are re-used,
so
if you use :foo in your application 100 times, it’s only in memory once.
Whereas if you use “foo” 100 times, it’s in memory 100 times.
As it pertains to YAML, String keys and Symbol keys are stored
differently:
irb2.0.0> require ‘yaml’ #2.0.0 => true
irb2.0.0> puts({:symbol => “I am a Symbol”, ‘string’ => “I am a
String”}.to_yaml)
:symbol: I am a Symbol
string: I am a String #2.0.0 => nil
Note that there is actually a : (colon) in front of the :symbol and not
in front of the string. In both cases there is a : after the key and
before the value. (You might also note that the default value is a
string and quoting is often implied.)
Here are more types so you can see how they get formatted as YAML:
irb2.0.0> puts({:symbol => “I am a Symbol”, ‘string’ => “I am a String”,
42 => “I am the Answer”, “41” => “I am not a number”, “NumberFive” => 5,
“String5” => “5”, ’ quote me ’ => " I need quotes to keep my
leading/trailing spaces"}.to_yaml)
:symbol: I am a Symbol
string: I am a String
42: I am the Answer
‘41’: I am not a number
NumberFive: 5
String5: ‘5’
’ quote me ‘: ’ I need quotes to keep my leading/trailing spaces’ #2.0.0 => nil
Thanks guys, that has been very informative. Although, each example has
been symbols used in a hash array. Any other uses? Perhaps outside of a
“hash”? Thanks.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.