1
votes

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?

3
Symbols are immutable, but that's not the primary reason they're used. Symbols only have one instance; All occurrences of the same symbol point to the same spot in the variable space, so memory savings could be significant in a large application with a lot of instance variables.the Tin Man

3 Answers

3
votes

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 Strings for convenience reasons.

1
votes

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'

0
votes

Preference. Symbols require less effort to type and some IDE's highlight them with pretty colors.