Ruby's Symbols Explained
Why Stack Overflow recommends it
Stack Overflow users link it when answering newcomers' questions about what Ruby symbols are and how they differ from strings and variables.
Recommended by 2 people across 2 different months, 2013 to 2016.
What it is
A 25-minute excerpt from Peter Cooper's Ruby Reloaded course that explains what Ruby symbols are, how they differ from strings, and why they are useful. Cooper walks through the concepts with live examples.
What people said
Recommends nbit001 · 2013-09 · Stack Overflow · on “Why are symbols in Ruby not thought of as a type of variable?”
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
Recommends SteveTurczyn · 2016-01 · Stack Overflow · on “Rails newbie: What does "<<" mean?”
Ah, I misread your message... "." and ":" look very similar on my monitor! Anything with a leading `:` is a symbol, which is just a concept with a name. This video discusses symbols... it's not a perfect video but he does a good job... [this video]
Cites Cu1ture · 2014-07 · Stack Overflow · on “What is the difference bewtween var = 55 and :var = 55 in Ruby?”
I have just been watching this video ion Symbols [this video] in Ruby. In the video it seems to say that assigning a variable creates a symbol of the same name and points it the the respective object in the assignment. I understand the difference between as String and a Symbol, in that strings create unique objects every time where as Symbols always reference the same object. However I am struggling to understand the difference between a Variable and a Symbol of the same name. For example, how is: var = 55 Different from: :var = 55