Friday, July 12, 2013

Re: [Rails] Learning About Symbols


On 2013-Jul-12, at 14:53 , Peter wrote:


Are these true or false?
yaml['config'] == yaml[:config]
yaml['config']['another_setting'] == yaml[:config][:another_setting]

The answer to both is false.

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. 


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


-Rob

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate