Ruby Symbols

https://news.ycombinator.com/rss Hits: 6
Summary

Symbols and Why You Should Care# I should start, aptly, with the manual. A Symbol object represents a named identifier inside the Ruby interpreter. Okay, it鈥檚 a token of a sort, I think. I鈥檝e been befuddled when seeing :name instead of name and I didn鈥檛 know what it was at first. I spent some time reading Michael Hartl鈥檚 Learn Enough Ruby and I cannot really say I understood Symbols, so I wanted to RTFM. The same Symbol object will be created for a given name or string for the duration of a program鈥檚 execution, regardless of the context or meaning of that name. Thus, if Fred is a constant in one context , a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 module One class Fred end $f1 = :Fred end module Two Fred = 1 $f2 = :Fred end module Three def Fred() end $f3 = :Fred end puts $f1.object_id puts $f2.object_id puts $f3.object_id Running this code shows: 18152204 18152204 18152204 All three symbols have the exact same object_id, proving they鈥檙e the same object in memory despite Fred being a class, a constant, and a method in different contexts. Does that mean all three symbols are the exact same object? At first glance, :Fred seems to be the thing that identifies the class, variable or the method. But let鈥檚 expand our example to version 2, where each module has a method that uses the symbol :Fred to interact with whatever Fred means in that context. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 module One class Fred def greet "Hello from Fred the class!" end end def self.use_fred_symbol # Use the symbol :Fred to get the class klass = const_get(:Fred) instance = klass.new puts "In module One, using symbol :Fred to get the class" puts "const_get(:Fred) returns: #{klass.class}" puts "Creating instance: #{instance.greet}" :Fred...

First seen: 2025-11-18 10:49

Last seen: 2025-11-18 15:50