Jiang Yan
Jiang Yan

Reputation: 11

Is there any difference between foo[:product] = "abc" and foo["product"] = "abc" in ruby on rails

Notice, it's not difference between product = "abc" and product = :abc.

it's foo[:product] = "abc" and foo["product"] = "abc", so the question is more about Ruby on rails script parser. Does RoR also cache/hash class property name?

Upvotes: 1

Views: 147

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369536

No, there is no difference. Both of these are simply SyntaxErrors, since neither :product nor "product" is a legal variable name:

"product" = "abc"
# SyntaxError: syntax error, unexpected '=', expecting $end
# "product" = "abc"
#            ^

:product = "abc"
# SyntaxError: syntax error, unexpected '=', expecting $end
# :product = "abc"
#           ^

Upvotes: 0

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

A normal Ruby Hash will differentiate between the keys :product and "product". An instance of ActiveSupport::HashWithIndifferentAccess will consider both of those as the same key.

You can call #with_indifferent_access on a Hash to convert it, but be aware that you can lose key/value pairs when doing so.

Upvotes: 7

Related Questions