Skylerclayne Skylerclayne - 1 month ago 6x
Ruby Question

Ruby and Chef difference in hashes

I've been programming in ruby for a little while now and have heard that using symbols for accessing values in hashes is a "better practice" than using strings, e.g.

default[:key] = value
default['key'] = value

I've been working on a chef project and noticed that chef cookbooks use the second way to access hash values (via strings). Often accessing via the symbol alternative does not work!

So I guess my question is two part, should I stop using symbols and use string accessors everywhere? And why does the use of symbols not work?


T.L;D.R. Accessing attributes by symbol is discouraged in favor of strings, despite still in use.

Quoting lamont granquist from Chef in a foodcritic (linter) issue here

Chef implementation of Mashes converts all symbols internally to strings

The official recommendation in docs is to use Strings.

To complete the Overview of chef attributes you can also access them as instance method, I.e. node.key.subkey but this method is deprecated and will be removed in short to mid term.