[ ruby ] Symbol v.s. String

Prefixed with a colon. Examples – :action, :line_items

  • Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.
puts "string".object_id
puts "string".object_id
puts :symbol.object_id
puts :symbol.object_id

Finding all symbol at this moment.

Symbol.all_symbols

Example : 

know_ruby = :yes
if know_ruby == :yes
puts 'You are a Rubyist'
else
puts 'Start learning Ruby'
end

is better than

know_ruby = 'yes'
if know_ruby == 'yes'
puts 'You are a Rubyist'
else
puts 'Start learning Ruby'
end

Every mention of ‘yes’ creates a new object stored separately in memory, whereas symbols are single reference values that are only initialized once.

Using symbol as Hash Key

h = {:nickname => 'IndianGuru', :language => 'Marathi', :lastname => 'Talim'}

or

h = {nickname: 'IndianGuru', language: 'Marathi', lastname: 'Talim'}

An exception to the shorter {symbol: value} syntax is when you would like to use a numeric key:

hash = {1: 'one'} # will not work
hash = {1 => 'one'} # will work 

ref : http://rubylearning.com/satishtalim/ruby_symbols.html,

http://rubylearning.com/satishtalim/ruby_hashes.html,

http://rubylearning.com/blog/2007/11/26/akitaonrails-on-ruby-symbols/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s