Dr.Strangelove
Dr.Strangelove

Reputation: 1495

Why is there no conversion of nil to symbol in Ruby?

Given that nil.to_s is an empty string '' and :"".to_s is an empty string as well, I can't help but wonder why nil.to_sym gives an error. It seems logical to me that nil.to_sym would give an empty symbol :"". Am I missing something or could this be a useful drop-in extension of NilClass?

Upvotes: 3

Views: 2217

Answers (1)

sawa
sawa

Reputation: 168249

Until recent, symbols, unlike strings, could not be garbage collected, so people had to be more careful about generating symbols from some random object. Symbol is to be used when its inventory is predetermined; it is not supposed to be used to express an open range of objects.

Recently, garbage collection for symbols was introduced, but you still don't need nil.to_sym; if your purpose is just to safely apply a symbol class's instance method, then you don't need to convert it to a symbol first as you can just use the safety navigation operator on it.

foo&.some_symbol_method

Upvotes: 3

Related Questions