dude0faw3
dude0faw3

Reputation: 129

Referencing hash elements with symbol keys versus string keys

How come ruby doesn't let you reference an element with either a string or a symbol unambiguously? This has often come up to bite me, especially when dealing with JSON. Doing

hash = {stat: bar}

allows for a reference by hash[:stat]. Later, if I did this:

hash = JSON.parse(hash.to_json)
hash[:stat]

that would return nil, and instead I would have to do hash['stat']. Why is that? Was this intentional, and if so, why?

Upvotes: 1

Views: 531

Answers (3)

Jörg W Mittag
Jörg W Mittag

Reputation: 369478

A hash maps key objects to value objects. If you associate a value object with a key object, you can retrieve it via that key object. If you associate a value with a different key object, you can retrieve it via that different key object. Passing one key object and getting the value of a different key object is just plain wrong.

Take, for example, the following hash:

hsh = {:foo => 42, 'foo' => 23, [:foo] => :bar, ['foo'] => :baz}

How would you retrieve either 42 or 23 if Ruby just willy-nilly started returning values for totally different keys?

Upvotes: 4

user229044
user229044

Reputation: 239312

JSON has no symbols. For property names, it only has strings. When you serialize a key/value pair to a JSON object, you lose any information about whether the key started life as a string or symbol, the key is just a string. When you deserialize the object back into a Ruby data structure, the only sane choice is to use strings for keys.

Upvotes: 3

cevado
cevado

Reputation: 62

Symbol is parsed as string to json but the json parsed to hash will see it as string. If you gonna use it both ways, it's better to freeze the string instead of using symbols.

Upvotes: -2

Related Questions