Having trouble understanding symbols in Ruby?
There’s lots of material out there trying to help Ruby newcomers understand symbols, but I thought this little bit of code might help clear things up:
class Foo
attr_accessor :test
def initialize
puts :test.object_id
end
end
class Bar
attr_accessor :test
def initialize
puts :test.object_id
end
end
b = Foo.new
c = Bar.new
The initialize method of each of these classes prints out the id of the :test symbol, which will always be the same because a symbol is just a globally unique identifier. Foo and Bar can have different values for test, the symbol :test is just used by the attr_accessor method to generate getters and setters. ActionScript developers who are familiar with using objects as keys in a Dictionary will notice some similarities.




1 year ago
