Reputation: 27852
So why would we do this in Ruby:
attr_accessor :price
Instead of:
attr_accessor 'price'
I have read that Symbols are similar to Strings, but they are immutable. But I fail to see why would we use that when doing attr_accessor, attr_reader. I mean, what are the advantages?
Upvotes: 1
Views: 792
Reputation: 369556
It's just the right thing to do. Symbol
is a data type whose purpose is specifically to represent the concept of a "name" or "label". Here, you are using it to pass the name of a pair of methods to generate. Symbol
is just the correct data type in this case. The methods also take String
s for convenience reasons.
Upvotes: 3
Reputation: 11495
Symbols are interned, unlike strings, so you avoid creating a ton of (potentially) duplicate string objects. Using the same :foo
symbol in several places does not consume more memory at a constant rate, unless doing the same with 'foo'
Upvotes: 1
Reputation: 19546
Preference. Symbols require less effort to type and some IDE's highlight them with pretty colors.
Upvotes: 0