New to programming and to Ruby, and I hope this question about symbols is in line. I understand that symbols in Ruby (e.g., :book, :price) are usef
Cool, I guess you understand them by now. However why are they so important?
Symbols in Ruby are immutable whereas strings are mutable. You think ok cool, so what?
Let's assume you have an array of strings, like so:
[ "a", "b", "a", "b", "a", "b", "c" ]
For each new string you create ruby is going to create a string/object which holds the value of "a" and because strings are mutable things ruby assigns a different id to each of them. If you were to use symbols instead:
[ :a, :b, :a, :b, :a, :b, :c ]
Ruby now will point to those symbols and it will only create them once.
Let's do some benchmarking:
require 'benchmark'
Benchmark.bm do |x|
x.report("Symbols") do
a = :a
1000_000.times do
b = :a
end
end
x.report("Strings") do
a = "a"
1000_000.times do
b = "a"
end
end
end
ruby -w symbols.rb
Symbols 0.220000 0.000000 0.220000 ( 0.215795)
Strings 0.460000 0.000000 0.460000 ( 0.452653)
If you'd like to see all the symbols you have already created you could do:
Symbol.all_symbols
You can also send a message to them asking about their id:
:a.object_id #=> 123
:a.object_id #=> 123
"a".id #=> 23323232
"a".id #=> some_blob_number
Again that's because Strings in Ruby are mutable and Symbols are not. Ruby Symbols represent names inside the Ruby Interpreter.
This video really helped me: Ruby's Symbols Explained
I hope it helps you all.