Tech

Symbols!!! [Ruby Programming Language Notes]

Symbols in Ruby

  • Symbols are an additional data type, similar to strings, but different.
  • str = ” “ strings are wrapped in quotes.
  • Symbol = : symbols begin with a colon.
  • Ex:
    • str = “hello # the string
    • sym = :hello # the symbol
    • p str.length # => 5
    • p sym.length # => 5
    • p str[1] # => “e”
    • p sym[1] # => “e”
    • p str == sym # => false
    • #Lesson…A string is DIFFERENT from a symbol!

Strings are mutable (can be changed, or mutated).

Symbols are immutable (can never be changed, or mutated).

Because strings are mutable, they are always stored in a new memory location (even if spelled the same).

Symbols are stored in exactly one memory location. Because of this, symbols can be more efficient with memory.