Ruby Symbols
10 days ago
- #ruby
- #metaprogramming
- #symbols
- Symbols in Ruby are named identifiers that remain the same object throughout a program's execution, regardless of context.
- Symbols like :Fred can represent different things (class, constant, method) but always refer to the same object in memory.
- Ruby uses symbols for metaprogramming, enabling dynamic method calls (e.g., obj.send(:method_name)) and runtime reflection.
- Symbols are more efficient than strings for hash keys because they reuse memory, unlike strings which create new objects.
- Ruby's attr_accessor uses symbols to dynamically generate getter and setter methods at runtime.
- Symbols can be converted to procs using the & operator, enabling concise method calls like [1, 2, 3].map(&:to_s).
- Ruby's symbols are similar to atoms in Erlang/Elixir and keywords in Clojure, serving as immutable identifiers.
- Symbols were historically prone to memory leaks, but Ruby 2.2 introduced garbage collection for dynamically created symbols.
- Symbols are deeply integrated into Ruby's design, inherited from Smalltalk and Lisp, for protocol-based programming.
- Rails uses symbols to define enums, leveraging Ruby's metaprogramming capabilities for clean, expressive code.