Jamie Forrest
Jamie Forrest

Reputation: 11113

Why are empty Arrays and Hashes treated differently when cast to string and then to symbol?

In Ruby, why are these two operations different for empty Arrays and Hashes?

Empty Array:

[].to_s.to_sym => :[] 

Empty Hash:

{}.to_s.to_sym => :"{}"

Upvotes: 3

Views: 94

Answers (2)

Emily
Emily

Reputation: 18203

They aren't really different, it's just that they're displayed differently. The { character can't be the start of a symbol, so it's enclosed in quote marks. It's the same thing you'd do if you wanted to create a symbol that had a - in it, since otherwise it would be interpreted as the subtraction operator. In fact, you can go into IRB and test that the quotes don't really affect the symbol.

:[] == :"[]" #=> true

So, basically, one is able to use a shorter form, and the other has to be more verbose so that the parser can understand it. But there's not an essential difference in the meaning or form of the two.

Upvotes: 8

Pavel Strakhov
Pavel Strakhov

Reputation: 40512

Because string representation of [] is "[]" and string representation of {} is "{}". By the way, :[] is equal to :"[]". The difference is that you can write symbol :"[]" without parenthesis, but you can't do it for :"{}", Ruby syntax disallow that.

Upvotes: 4

Related Questions